Count all items inside a collection entry

Viewed 37

I have the collection:

    {'_id':'1',
     'n1':'a',
     'f4':'4rrf'},

    {'_id':2
     'k545':'aad5',
     '1dd':'1s',
     '1yh':'sxaa',
     '6uu':'jt',
     }]

Where all the entries are nested at the same level as '_id', I would like a query that count all the entries per '_id', with the following output:

{'_id':1,
 'count':2},
{'_id':2,
 'count':4
}
1 Answers

Use Aggregation Framework which has a array $size operator which you can use:

> db.mycollection.aggregate([{$project: { count: { $size:"$_id" }}}])
Related