Search code examples
javascriptnode.jsmongodbmongodb-querynode-mongodb-native

elemMatch search on array of subdocument


How to do search using elemMatch on array of SubDocument? I have document called ReportCollection with elements such as:-

/* 0 */
{
    "_id" : ObjectId("5507bfc435e9470c9aaaa2ac"),
    "owner" : ObjectId("5507bfc31e14d78e177ceebd"),
    "reports" : {
        "xReport" : [ 
            {
                "name" : "xReport",
                "parameters" : {
                    "x" : {
                        "dateTime" : "2015-03-11T18:30:00.000Z",
                        "unit" : 1,
                        "value" : 102
                    }
                },
                "createdBy" : ObjectId("5507bfc31e14d78e177ceebd"),
                "modifiedBy" : ObjectId("5507bfc31e14d78e177ceebd"),
                "_id" : ObjectId("5507bfc41e14d78e177ceebf")
            }
        ]
    }
}

I got reports.xReport[]._id as search parameter.

My following attempt is failing :-

  db.reports.find ({ {owner: ObjectId("5507afd3d54bae3513c185cb")}, 
    { 'reports.xReport': {$elemMatch: {_id: ObjectId("5507afd3d54bae3513c185cd") }}} } )

Solution

  • It seems like you are trying to put work into the "projection" that you should be doing in the query. Rather your statement should look more like this:

    db.reports.find(
        {
            "owner": ObjectId("5507bfc31e14d78e177ceebd"),
            "reports.xReport._id": ObjectId("5507bfc41e14d78e177ceebf")
        },
        { "reports.xReport.$": 1 }
    )
    

    So the "query" does the work of matching the array position and the "projection" just uses that position in the match.

    Also note that you never really need $elemMatch with a single field to match against. Only when multiple fields are required in the condition do you need to use this to match a specific "element".

    By the same token, that should also be in the "query" statement instead.

    $elemMatch in it's projected form cannot be used with sub-document fields through dotted notation.