MongoDB:计算数组中的项目数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21387969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:34:34  来源:igfitidea点击:

MongoDB: count the number of items in an array

mongodbmongoid

提问by randombits

I have a collection where every document in the collection has an array named foothat contains a set of embedded documents. Is there currently a trivial way in the MongoDB shell to count how many instances are within foo? something like:

我有一个集合,其中集合中的每个文档都有一个名为的数组foo,其中包含一组嵌入文档。目前在 MongoDB shell 中是否有一种简单的方法来计算其中有多少个实例foo?就像是:

db.mycollection.foos.count()or db.mycollection.foos.size()?

db.mycollection.foos.count()或者db.mycollection.foos.size()

Each document in the array needs to have a unique foo_idand I want to do a quick count to make sure that the right amount of elements are inside of an array for a random document in the collection.

数组中的每个文档都需要有一个唯一的foo_id,我想快速计数以确保正确数量的元素位于集合中随机文档的数组内。

回答by Stennie

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

在 MongoDB 2.6 中,聚合框架有一个新的数组$size运算符,您可以使用:

> 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 }

回答by xlembouras

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

如果您使用的是最新版本的 mongo(2.2 及更高版本),则可以使用聚合框架。

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.

这将为foo您提供收藏的总数。

Omitting the last groupwill aggregate results per record.

省略最后一个group将汇总每条记录的结果。