Mongodb - count of items using addToSet
I am grouped by organization
and used $addToSet
to show a distinct machineIds
one related to it organization
. I would like to get a counter machineIds
for each organization
. However, the code below returns a count of all machineIds
, not the number of individuals. Is there any other way to get the overall unique machineIds
?
db.getCollection('newcollections').aggregate([{
$group: {
_id: {
organization: "$user.organization"
},
machineId: {
"$addToSet": "$user.machineId"
},
count: {
$sum: 1
}
}
}])
source to share
You need to use the $ size operator in the projection as shown below:
db.collection.aggregate([{
$group: {
_id: {
organization: "$user.organization"
},
machineId: {
"$addToSet": "$user.machineId"
}
}
}, {
$project: {
"organization": "$_id.organization",
"machineId": 1,
"_id": 0,
"size": {
$size: "$machineId"
}
}
}])
source to share