Mongodb - count of items using addToSet

2019-02-14 03:31发布

问题:

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
    }
    }
}])

回答1:

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"
    }
    }
}])