如果我想对 MongoDB 中的数值求和,我会这样做:
totalOpenBalance: {
$sum: "$openBalance"
} // sum up all "openBalance" values
但我想知道的是,当我想要总结某物的实例时,我应该使用什么运算符?假设我有一个诸如 customer_id
之类的属性,以及如下所示的数据:
{
"customer_id" : 445,
"other_prop" : value
},
{
"customer_id" : 446,
"other_prop" : value
},
请注意,我不想对分配给“customer_id”的值进行求和,而是计算数据集合中有多少个“customer_id”实例。换句话说,根据上面的数据,我应该得到“2”作为我的输出。我应该使用什么运算符来执行此操作?
为了澄清,这是我需要添加到用于生成 mongo View 的聚合管道中的步骤。
最佳答案
以下任何一项都可以帮助您:
简单查找
:
db.collection.find({
"customer_id": { $exists: true }
}).count()
与$count
聚合:
db.collection.aggregate({
$match: {
"customer_id": { $exists: true }
}
}, {
$count: "numberOfInstances"
})
与$group
聚合:
db.collection.aggregate({
$match: {
"customer_id": { $exists: true }
}
}, {
$group: {
_id: null,
"numberOfInstances": { $sum: 1 } // count instances
}
})
关于javascript - 如何计算 MongoDB 中的实例数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50031244/