how to count number of sub object (same document) in mongodb

1.1k views Asked by At

Example document:

{
    "aliases" : {
        "name" : [ 
            "Brinton McKay", 
            "Dr. Theopolis", 
            "Galactic Spiral Sound", 
            "Highrise", 
            "Memory Boy", 
            "Semblance Factor", 
            "Spy (2)", 
            "Three O'Clock High"]}
}

How i can count the number of "name" under "aliases"? I would like to print all _id who which contains more than 3 aliases. any help would be appreciated.

1

There are 1 answers

5
Yathish Manjunath On

Please check the below query :

db.collection.find({ $where : function() 
{ return Object.keys(this.aliases.name).length > 3 } });

OR

db.collection.aggregate([
{$project : { _id :1 , numb : {$size : "$aliases.name"} }
},
{$match : { numb :{$gt : 3 }}
}
]);

PS : you can see the documentation in below link : http://docs.mongodb.org/manual/reference/operator/query/where/