我可以从MongoDb获得前10名的成员名单

时间:2018-02-16 11:37:13

标签: mongodb mongoose mongodb-query mongoose-schema mongoose-populate

我有2个集合,一个用于组详细信息,另一个用于group_members详细信息, group_members存储了组_id(作为FK)

像 组: - > _id,名称,类型,日期

group_members - > _id,GROUP_ID,members_id,角色,状态

那么如何通过group_membrs的计数(前10名成员更多的组)来获得那些拥有最多memebrs的团体

1 个答案:

答案 0 :(得分:1)

因此,如果groupMembers集合包含您描述的组ID,例如:

var r = [
 {_id: "M1", gid: "A", member: "Bob"}
 ,{_id: "M2", gid: "A", member: "Sally"}
 ,{_id: "M3", gid: "A", member: "Dan"}
 ,{_id: "M4", gid: "B", member: "Tess"}
 ,{_id: "M5", gid: "B", member: "George"}
 ,{_id: "M6", gid: "C", member: "P_1"}
 ,{_id: "M7", gid: "C", member: "P_2"}
 ,{_id: "M8", gid: "C", member: "P_3"}
 ,{_id: "M9", gid: "C", member: "P_4"}
 ];
 db.foo2.insert(r);

然后,这就是你如何得到每组的计数:

c=db.foo2.aggregate([
  {$group: {_id: "$gid", n: {$sum:1} }}
  ,{$sort: {n: -1}}
  ,{$limit: 10}
]);

如果我们投入组主集合,例如

var r = [
     {_id: "A", name: "GroupA"}
     ,{_id: "B", name: "GroupB"}
     ,{_id: "C", name: "GroupC"}
];
db.foo.insert(r);

然后我们只需$lookup来“加入”数据:

db.foo2.aggregate([
  {$group: {_id: "$gid", n: {$sum:1} }}
  ,{$sort: {n: -1}}
  ,{$limit: 10}
  ,{$lookup: { from: "foo", localField: "_id", foreignField: "_id", as: "X"}}
]);

这会产生这样的结果:

{
"_id" : "C",
"n" : 4,
"X" : [
    {
        "_id" : "C",
        "name" : "GroupC"
    }
]
}
{
"_id" : "A",
"n" : 3,
"X" : [
    {
        "_id" : "A",
        "name" : "GroupA"
    }
]
}