Mongodb - count of items using addToSet

2019-02-14 03:52发布

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条回答
Explosion°爆炸
2楼-- · 2019-02-14 04:12

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"
    }
    }
}])
查看更多
登录 后发表回答