问题的简化示例
您好,
使用mgo将文档插入mongodb,我试图将文档嵌入到另一个文档中。
使用mgo,我可以使用两个结构:
type Test struct {
InTest SubTest `bson:"in_test"`
}
type SubTest struct {
Test1 string `bson:"test1"`
Test2 string `bson:"test2"`
}
然后我插入一份文件:
test := Test{InTest: SubTest{Test1: "test", Test2: "hello"}}
err = col.Insert(test)
if err != nil {
fmt.Printf("Can't insert document: %+v\n", err)
os.Exit(1)
}
现在,我想根据嵌入式文档中的字段找到此文档:
var tests []Test
err = sess.DB("test ").C("test").Find(
bson.M{"in_test": bson.M{"test1": "test"}}).All(&tests)
if err != nil {
fmt.Printf("Got an error finding documents %+v\n")
os.Exit(1)
}
fmt.Printf("Found document: %+v\n", tests)
打印:Found document: []
使用两个字段进行搜索会返回文档:
var tests []Test
err = sess.DB("test").C("test").Find(
bson.M{"in_test": bson.M{"test1": "test", "test2": "hello"}}).All(&tests)
if err != nil {
fmt.Printf("Got an error finding documents %+v\n")
os.Exit(1)
}
fmt.Printf("Found document: %+v\n", tests)
打印:Found document: [{InTest:{Test1:test Test2:hello}}]
我已尝试以bson.M格式插入文档,但结果相同:
type Test struct {
InTest bson.M `bson:"in_test"`
}
test := Test{InTest: bson.M{"test1": "test", "test2": "hello"}}
err = col.Insert(test)
if err != nil {
fmt.Printf("Can't insert document: %+v\n", err)
os.Exit(1)
}
var tests []Test
err = sess.DB("test").C("test").Find(
bson.M{"in_test": bson.M{"test1": "test"}}).All(&tests)
if err != nil {
fmt.Printf("Got an error finding documents %+v\n")
os.Exit(1)
}
fmt.Printf("Found document: %+v\n", tests)
再次打印:Found document: []
如果搜索两个字段,则为Found document: [{InTest:map[test1:test test2:hello]}]
如何在嵌入式结构/文档中找到与ONE字段匹配的文档?
提前致谢!
答案 0 :(得分:2)
您的初始问题具有误导性,您需要匹配子文档:
func main() {
sess, err := mgo.Dial("localhost")
if err != nil {
fmt.Printf("Can't connect to mongo, go error %v\n", err)
os.Exit(1)
}
col := sess.DB("test").C("test")
test := Test{InTest: SubTest{Test1: "test", Test2: "hello"}}
err = col.Insert(test)
if err != nil {
fmt.Printf("Can't insert document: %+v\n", err)
os.Exit(1)
}
var tests []Test
err = col.Find(bson.M{"in_test.test2": "hello"}).All(&tests)
fmt.Println(tests)
}