-1

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.

2
  • 1
    Take a look at this answer.
    – bagrat
    Commented Jun 10, 2015 at 22:07
  • So in this case it would be: db.coll.find({'aliases.name.3': {$exists: true}})
    – JohnnyHK
    Commented Jun 11, 2015 at 12:30

1 Answer 1

0

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/

5
  • This is the error: error: { "$err" : "Can't canonicalize query: BadValue $size needs a number", "code" : 17287 }
    – mrana
    Commented Jun 11, 2015 at 11:54
  • can you check the above query ? Commented Jun 11, 2015 at 12:16
  • It works but as { $size: 3 } not as {$size:{$gt:3}} , how i can use $gt? Thanks very much
    – mrana
    Commented Jun 11, 2015 at 12:20
  • I have posted anothet query using aggregate function, can you check that as well. I have edited that in my post. please try them. Commented Jun 11, 2015 at 12:23
  • This one is perfect: db.coll.find({'aliases.name.3': {$exists: true}}) Great JohnnyHK & also Yathish. You guys are good.
    – mrana
    Commented Jun 13, 2015 at 22:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.