本文介绍了Mongodb-使用addToSet的项目计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我按organization
分组,并使用$addToSet
来显示与该organization
相关的独特的machineIds
.我想获取每个organization
的machineIds
计数.但是,下面的代码将返回所有machineIds
的计数,而不是不同的计数.是否有另一种方法来获取总的唯一machineIds
?
I grouped by organization
and used $addToSet
to show the distinct machineIds
associated with that organization
. I would like to get the count of machineIds
for each organization
. However the code below is returning a count of all machineIds
, not the count of distinct ones. Is there another way to get the total unique machineIds
?
db.getCollection('newcollections').aggregate([{
$group: {
_id: {
organization: "$user.organization"
},
machineId: {
"$addToSet": "$user.machineId"
},
count: {
$sum: 1
}
}
}])
推荐答案
您需要使用 $ size 运算符如下:
You need to use $size operator in projection like following:
db.collection.aggregate([{
$group: {
_id: {
organization: "$user.organization"
},
machineId: {
"$addToSet": "$user.machineId"
}
}
}, {
$project: {
"organization": "$_id.organization",
"machineId": 1,
"_id": 0,
"size": {
$size: "$machineId"
}
}
}])
这篇关于Mongodb-使用addToSet的项目计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!