问题的简化示例嗨,使用 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 []Testerr = 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 []Testerr = 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 []Testerr = 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]}]如果搜索两个字段如何在嵌入的结构/文档中找到与一个字段匹配的文档?提前致谢!
1 回答
- 1 回答
- 0 关注
- 186 浏览
添加回答
举报
0/150
提交
取消