MongoDB: count the number of items in an array

前端 未结 3 1917
执笔经年
执笔经年 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:30

    if you are on a recent version of mongo (2.2 and later) you can use the aggregation framework.

    db.mycollection.aggregate([
      {$unwind: '$foo'},
      {$group: {_id: '$_id', 'sum': { $sum: 1}}},
      {$group: {_id: null, total_sum: {'$sum': '$sum'}}}
    ])
    

    which will give you the total foos of your collection.

    Omitting the last group will aggregate results per record.

提交回复
热议问题