Mongodb Aggregation count array/set size

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

提交回复
热议问题