问题的简化示例
你好,
使用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]}]
(如果同时搜索两个字段)如何在嵌入式结构/文档中找到与一个字段匹配的文档?
提前致谢!
最佳答案
您最初的问题有误导性,您需要匹配子文档:
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)
}
关于mongodb - mgo,mongodb : Finding documents that match one field from embedded struct,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26433463/