MongoDb - $match filter not working in subdocument

Posted by Ranjith on Stack Overflow See other posts from Stack Overflow or by Ranjith
Published on 2014-08-21T09:28:41Z Indexed on 2014/08/21 10:20 UTC
Read the original article Hit count: 262

This is Collection Structure

[{
   "_id"              : "....",
   "name"             : "aaaa",
   "level_max_leaves" : [
                           {
                              level      : "ObjectIdString 1",
                              max_leaves : 4,
                           }
                        ]
},
{
   "_id"              : "....",
   "name"             : "bbbb",
   "level_max_leaves" : [
                           {
                              level      : "ObjectIdString 2",
                              max_leaves : 2,
                           }
                        ]
}]

I need to find the subdocument value of level_max_leaves.level filter when its matching with given input value.

And this how I tried,

For example,

var empLevelId = 'ObjectIdString 1' ;

MyModel.aggregate(
    {$unwind: "$level_max_leaves"},
    {$match: {"$level_max_leaves.level": empLevelId } },
    {$group: { "_id": "$level_max_leaves.level", 
               "total": { "$sum": "$level_max_leaves.max_leaves" }}},
    function (err, res) {
        console.log(res);
});

But here the $match filter is not working. I can't find out exact results of ObjectIdString 1

If I filter with name field, its working fine. like this,

{$match: {"$name": "aaaa" } },

But in subdocument level its returns 0.

{$match: {"$level_max_leaves.level": "ObjectIdString 1"} },

My expected result was,

{
   "_id"              : "ObjectIdString 1",
   "total"            : 4,
}

© Stack Overflow or respective owner

Related posts about node.js

Related posts about mongodb