MongoDB:计算数组中的项目数 [英] MongoDB: count the number of items in an array

查看:65
本文介绍了MongoDB:计算数组中的项目数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个集合,集合中的每个文档都有一个名为foo的数组,该数组包含一组嵌入式文档. MongoDB Shell中当前是否有一种简单的方法来计算foo中有多少个实例?像这样:

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 the MongoDB shell to count how many instances are within foo? something like:

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

数组中的每个文档都必须具有唯一的foo_id,我想进行一次快速计数,以确保集合中随机文档的数组中包含正确数量的元素.

Each document in the array needs to have a unique foo_id and 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.

推荐答案

在MongoDB 2.6中,聚合框架具有一个新数组

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 }

这篇关于MongoDB:计算数组中的项目数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆