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
}
}
}])
MongoDB $count Aggregation First, we invoke the $count operator and then specify the string. In this syntax, 'the_string' represents the label or the name of the output field. It must be non-empty and cannot start with a dollar sign '$' or dot '. ' character.
The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array. The $addToSet operator has the form: { $addToSet: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.
In MongoDB, when we have a large dataset inside the collection and we want to count where the field value is repeating on multiple fields then we use $group aggregation. Example: Here, we are taking an example in which we apply $group aggregation with multiple fields and get the count of duplicate field values.
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"
}
}
}])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With