Mongodb Aggregation count array/set size

前端 未结 3 1536
花落未央
花落未央 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:41

    The following will return number of uniqueUsers per application. This will apply an group operation to a result of a group operation by using pipeline feature of mongodb.

    { $match: { application: "abc" } }, 
    { $unwind: "$users" }, 
    { $group: { _id: "$status", users: { $addToSet: "$users" } } }, 
    { $unwind:"$users" }, 
    { $group : {_id : "$_id", count : {$sum : 1} } }
    

    Hopefully this will be done in an easier way in the following releases of mongo by a command which gives the size of an array under a projection. {$project: {id: "$_id", count: {$size: "$uniqueUsers"}}} https://jira.mongodb.org/browse/SERVER-4899

    Cheers

    0 讨论(0)
  • 2021-02-05 18:45

    Sorry I'm a little late to the party. Simply grouping on the 'user_id' and counting the result with a trivial group works just fine and doesn't run into doc size limits.

    [
        {$match: {application: 'abc', date: {$gte: startDate, $lte: endDate}}},
        {$unwind: '$user_id'},
        {$group: {_id: '$user_id'}},
        {$group: {_id: 'singleton', count: {$sum: 1}}}
    ];
    
    0 讨论(0)
  • 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"}
            }
        }
    ]
    
    0 讨论(0)
提交回复
热议问题