[英]How to Count Instances in MongoDB
If I want to sum up numerical values in MongoDB I do it like this: 如果我想对MongoDB中的数值求和,可以这样:
totalOpenBalance: {
$sum: "$openBalance"
} // sum up all "openBalance" values
But what I'm wondering is, what operator do I use when I want to sum up instances of something? 但是我想知道的是,当我要总结某些实例时,该使用什么运算符? Say if I have a property such as customer_id
, and data that looks like this: 假设我具有诸如customer_id
的属性,并且数据看起来像这样:
{
"customer_id" : 445,
"other_prop" : value
},
{
"customer_id" : 446,
"other_prop" : value
},
Note that I don't want to sum up the values assigned to "customer_id", but rather tally up how many instances of "customer_id" are in the collection of data. 请注意,我不想汇总分配给“ customer_id”的值,而是计算数据集中有多少“ customer_id”实例。 In other words, according to the data above, I should get "2" as my output. 换句话说,根据上面的数据,我应该将“ 2”作为输出。 What operator do I use to do that? 我要用什么运算符来做到这一点?
To clarify, this is a step I need to add to an aggregation pipeline I'm using to generate a mongo view. 为了澄清,这是我需要添加到用于生成mongo视图的聚合管道的步骤。
Any of the below should get you going: 以下任何一项都可以助您一臂之力:
Simple find
: 简单find
:
db.collection.find({
"customer_id": { $exists: true }
}).count()
Aggregate with $count
: 用$count
汇总:
db.collection.aggregate({
$match: {
"customer_id": { $exists: true }
}
}, {
$count: "numberOfInstances"
})
Aggregate with $group
: 与$group
聚合:
db.collection.aggregate({
$match: {
"customer_id": { $exists: true }
}
}, {
$group: {
_id: null,
"numberOfInstances": { $sum: 1 } // count instances
}
})
You can simply use find
and $exists
and then count the returned rows 您可以简单地使用find
和$exists
,然后计算返回的行
db.collection.find( { customer_id: { $exists: true } } ).count()
Or if you want to use aggregate (which I don't think you should do for such simple task) this is how you can do it. 或者,如果您想使用聚合(我不认为您应该为如此简单的任务做),这就是您可以做到的。
db.collection.aggregate({ $match: { "customer_id": { $exists: true } } }, { $group: { _id: null, "total": { $sum: 1 } } })
Here total
property will give you the number of instances containing customer_id
in them 这里的total
属性将为您customer_id
其中包含customer_id
的实例数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.