Search code examples
mongodbgobsonmgo

Issue getting entire element from mongo using golang bson instead only child element is being returned


I am working on a mongo query in golang using mgo to query a child element to return the entire element

{
    "_id" : ObjectId("5b64a0d3931653c36bcaf0b5"),
    "quantity" : 2,
    "product" : "ABC",   
    "children" : [ 
        {           
            "isBlocked" : true,
            "blockedMessage" : "Error occurred: TRACEID",
            "serialNo" : "abc123",
            "token" : "foo456",            
        }
    ]
}

The query I am using in below bson.M{"_id": 0, "children": bson.M{"$elemMatch": {serialNo: 'abc123'}}}

Find(MongoSpec{Selector: bson.M{}, Query: bson.M{"_id": 0, "children": bson.M{"$elemMatch": fields}}})

Below is the find function

    documents := []interface{}{}
        s := spec.(MongoSpec).Selector
        q := spec.(MongoSpec).Query
        query := session.
            DB(repo.Config.DatabaseName).
            C(repo.CollectionName).
            Find(s)

        if q != nil {
            query = query.Select(q)
        }

        err := query.All(&documents)

MongoSpec struct

  type MongoSpec struct {
        Selector interface{}
        Query    interface{}
    }

The above query works fine but returns only children element as below

"children" : [ 
            {           
                "isBlocked" : true,
                "blockedMessage" : "Error occurred: TRACEID",
                "serialNo" : "abc123",
                "token" : "foo456",            
            }
        ]

I am not getting what is wrong with the query.


Solution

  • $elemMatch exists as both a query and a projection. A query is used to actually filter which documents are returned, and a projection determines which part of the documents returned are shown. To reiterate: Projection doesn't filter which documents are returned, it limits which values per document are returned (similar to the SELECT part of SQL).

    mgo's Find function is the query, and Select is the projection. Therefore, you want your final code to look closer to this:

    c.Find(
        bson.M{
            "children": bson.M{
                "$elemMatch": bson.M{serialNo: "abc123"},
            },
        },
    ).Select(
        bson.M{
            "_id": 0,
        },
    )
    

    With how you have your code set up, this is how it would look.

    Find(
        MongoSpec{
            Selector: bson.M{"children": bson.M{"$elemMatch": fields}},
            Query: bson.M{"_id": 0},
        },
    )
    

    However, I'd strongly advise you rename the fields in MongoSpec (dropping it and the Find function altogether might not be a bad idea, too). You use Query as your projection (the .Select() function) and you use Selector as your query (.Find()). That may be why you made this mistake in the first place.