MongoDB: count the number of items in an array

前端 未结 3 1916
执笔经年
执笔经年 2020-11-22 10:08

I have a collection where every document in the collection has an array named foo that contains a set of embedded documents. Is there currently a trivial way in

3条回答
  •  攒了一身酷
    2020-11-22 10:31

    In MongoDB 2.6, the Aggregation Framework has a new array $size operator you can use:

    > db.mycollection.insert({'foo':[1,2,3,4]})
    > db.mycollection.insert({'foo':[5,6,7]})
    
    > db.mycollection.aggregate([{$project: { count: { $size:"$foo" }}}])
    { "_id" : ObjectId("5314b5c360477752b449eedf"), "count" : 4 }
    { "_id" : ObjectId("5314b5c860477752b449eee0"), "count" : 3 }
    

提交回复
热议问题