Mongoose - 按数组分组,按计数计数和排序

时间:2016-08-03 05:27:20

标签: mongodb mongoose aggregation-framework

我在 users 集合中有用户文档,如下所示

[
{
_id:"1",
user_name:"abc",
name:"ABC",
following:["xyz"]
},
{
_id:"2",
user_name:"xyz",
name:"XYZ",
following:[]
},
{
_id:"3",
user_name:"pqr",
name:"PQR",
following:["xyz","abc"]
}
]

我希望按跟随属性进行分组,计数然后排序 - 以便我获得大多数关注用户的文档,如下所示

[
{
_id:"2",
user_name:"xyz",
name:"XYZ",
followers_count:2
},
{
_id:"1",
user_name:"abc",
name:"ABC",
followers_count:1
},
{
_id:"3",
user_name:"pqr",
name:"PQR",
followers_count:0
}
]

1 个答案:

答案 0 :(得分:0)

db.users.aggregate([
                 {$unwind: "$following" },
                 {$group: { _id: "$following","username": {$first:"$user_name"},"name":  {$first:"$name"},followers_count:   { $sum: 1 } }},
                 {$project: {"name":"$name","user_name": "$username", _id:0, followers_count: 1 } },
                 {$sort: { followers_count: 1 } }
])

此外,

更新:

在您的情况下不需要使用group by pipeline,您可以通过

来实现
db.tests.aggregate([

                {
                  $project : { 
                                user_name:1, 
                                 name :1, 
                                 followingUsers: { $size: "$following" }  
                             }
                },
                {$sort: { followingUsers: 1 } }
])