Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb - count of items using addToSet

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
    }
    }
}])
like image 980
ellier Avatar asked Jul 01 '15 15:07

ellier


People also ask

Can we use count with aggregate function in MongoDB?

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.

How do you use $addToSet?

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.

How do I count multiple fields in MongoDB?

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.


1 Answers

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"
    }
    }
}])
like image 198
Vishwas Avatar answered Oct 02 '22 04:10

Vishwas