Mongoose-按数组元素分组,计数并按计数排序



我在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
}
]
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 } }
])

此外,

更新:

在您的情况下,不需要使用按管道分组,您可以通过实现相同的功能

db.tests.aggregate([
                {
                  $project : { 
                                user_name:1, 
                                 name :1, 
                                 followingUsers: { $size: "$following" }  
                             }
                },
                {$sort: { followingUsers: 1 } }
])

最新更新