Search code examples
mongodbgomgo

mgo, mongodb: Finding documents that match one field from embedded struct


SIMPLIFIED EXAMPLE OF ISSUE

Hi,

Using mgo to insert documents into mongodb, I'm trying to embed a document within another.

With mgo I'm using two structs for this like this:

type Test struct {
    InTest SubTest `bson:"in_test"`
}

type SubTest struct {
    Test1 string `bson:"test1"`
    Test2 string `bson:"test2"`
}

I then insert a document:

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

Now I'd like to find this document based on a field in the embedded document:

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)

This prints: Found document: []

Whereas searching using both fields returns the 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)

This prints: Found document: [{InTest:{Test1:test Test2:hello}}]

I've tried inserting the document in bson.M format as well but with the same results:

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)

Again printing: Found document: [] or Found document: [{InTest:map[test1:test test2:hello]}] if searching both fields

How do I find a document matching ONE field in an embedded struct/document?

Thanks in advance!


Solution

  • Your initial question was misleading, you need to match the subdocument:

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