1

问题的简化示例

你好,

使用 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 字段匹配的文档?

提前致谢!

4

1 回答 1

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)
}
于 2014-10-17T22:00:51.580 回答