打印MongoDB集合数据-GoLang,结果与预期不符

时间:2019-01-03 17:54:04

标签: mongodb go

我在Docker容器中有mongoDB,可以连接并更新数据库,我可以在Compass中查看结果。但是,在获取集合并打印结果时,它们不会像我期望的那样打印。

这是我的代码的片段:

db := client.Database("maccaption")
collection := client.Database("maccaption").Collection("JobBacklog")
res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"})
if err != nil {
    log.Fatal(err)
}
result := struct {
    Foo string
    Bar string
}{}
filter := bson.D{{"hello", "world"}}
err = collection.FindOne(context.Background(), filter).Decode(&result)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Results", result)

我正在使用官方的mongo-go-driver。并按照此处的示例https://godoc.org/github.com/mongodb/mongo-go-driver/mongo

我知道数据库已连接,当我添加到数据库时可以看到更新,然后在运行代码时它会显示在Compass中,但是当我期望时collection.FindOne返回Results {0}它返回hello: world

有人可以帮我吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

您插入的文档的字段名称为“ world”。然后,您尝试将该文档解压缩为具有Foo和Bar字段的结构。这些都没有命名为Hello,也没有bson标签,因此,应该在任何地方都无法解组Question: Which English king was "mad"? Answer: George III Question: Who started the Protestant Reformation? Answer: Martin Luther Question: Who was the first person to see the moons of Jupiter? Answer: Galileo Question: What Viking group settled in France before conquering England, Sicily, and Malta? Answer: The Normans Question: What group sacked Baghdad in 1258, ending the Islamic Golden Age? Answer: The Mongols Question: Against what city did Rome fight the Punic Wars? Answer: Carthage Question: What yellow gas was famously used in WWI? Answer: Mustard Gas Question: What epic poem is thought to be the oldest in the English language? Answer: Beowulf Question: What ancient empire was led by Xerxes, Cyrus, and Darius? Answer: Persia Question: Who was the most notorious member of the Ba'ath Party? Answer: Saddam Hussein Question: What Italian adventurer wrote about his 24 year journey from Venice to China and back? Answer: Marco Polo Question: What young pharaoh's tomb was discovered in 1922? Answer: Tutankhamun Question: Before becoming king of England, what country was James I the king of? Answer: Scotland Question: What was the primary language of the Byzantine Empire? Answer: Greek Question: For what crime was Al Capone convicted of in 1931? Answer: Tax Evasion 字段。如果您改为定义:

hello

它应该根据需要解组。