Mongodb Aggregation count array/set size

前端 未结 3 1541
花落未央
花落未央 2021-02-05 18:07

Here\'s my problem:

Model:

{ application: \"abc\", date: Time.now, status: \"1\" user_id: [ id1, id2, id4] }

{ application: \"abc\",

3条回答
  •  醉梦人生
    2021-02-05 18:50

    Use $size to get the size of set.

    [
        {
            $match: {"application": "abc"}
        },
        {
            $unwind: "$user_id"
        },
        {
            $group: {
                "_id": "$status",
                "application": "$application",
                "unique_user_id": {$addToSet: "$user_id"}
            }
        },
        {
            $project:{
                "_id": "$_id",
                "application": "$application",
                "count": {$size: "$unique_user_id"}
            }
        }
    ]
    

提交回复
热议问题