2016-08-03 94 views
0

我在用户收集用户文件如下所示猫鼬 - 由阵列元件组,计数和分类由计数

[ 
{ 
_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 
} 
] 

回答

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 } } 
]) 
+0

感谢您的答复achive相同。上述查询给我的回应 [ { “_id”: “XYZ”, “FOLLOWERS_COUNT”:2 }, { “_id”: “ABC”, “FOLLOWERS_COUNT”:1 } ] 我怎样才能得到用户的其他领域,如名称,_id等? –

+0

使用上面的查询 – rroxysam

+0

上面更新查询给了我'[ { “名”: “PQR”, “FOLLOWERS_COUNT”:1, “USER_NAME”: “焊接工艺评定” }, { “名”:“ ABC“, ”followers_count“:2, ”user_name“:”abc“ } ]' ]我需要名称和_id属性(以及followers_count)的用户被关注的不是追随者。 –