Mongodb - count of items using addToSet

前端 未结 1 999
挽巷
挽巷 2021-01-02 20:37

I grouped by organization and used $addToSet to show the distinct machineIds associated with that organization. I would l

相关标签:
1条回答
  • 2021-01-02 21:14

    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"
        }
        }
    }])
    
    0 讨论(0)
提交回复
热议问题