首页 文章

mgo,mongodb:查找与嵌入式结构中的一个字段匹配的文档

提问于
浏览
1

SIMPLIFIED EXAMPLE OF ISSUE

嗨,

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

提前致谢!

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)
    }
    

相关问题