Node.js 如何聚合数组中ObjectID的出现次数?

Node.js 如何聚合数组中ObjectID的出现次数?,node.js,mongodb,mongoose,mongodb-query,aggregation-framework,Node.js,Mongodb,Mongoose,Mongodb Query,Aggregation Framework,我有两个收藏用户和社区。我的用户可以链接到许多社区,因此我在用户架构中将linkedCommunities作为一个数组: const userSchema = new Schema({ linkedCommunities: [ { type: mongoose.Schema.ObjectId, ref: 'Community' } ] }); 在我的社区视图中,我想显示链接到每个社区的用户数,因此其内容如下: | Community | Nu

我有两个收藏<代码>用户和
社区
。我的用户可以链接到许多社区,因此我在用户架构中将
linkedCommunities
作为一个数组:

const userSchema = new Schema({
  linkedCommunities: [
    {
      type: mongoose.Schema.ObjectId,
      ref: 'Community'
    }
  ]
});
在我的
社区
视图中,我想显示链接到每个社区的
用户数
,因此其内容如下:

| Community   | Number of users |
| ---------   | --------------- |
| Community 1 | 45              | 
| Community 2 | 78              |
| Community 4 | 107             | 
理想情况下,当我在
社区
模型上查找时,我需要一个名为
linkedUserCount
的字段


我确信我可以通过使用
aggregate
以某种方式实现这一点,但我正在努力找到正确的管道操作符和顺序。

您可以通过使用以下mongodb查询来实现所需的结果:

db.users.aggregate( [ 
  { 
    $unwind : "$linkedCommunities" 
  },
  {
    $group : {
      _id : "$linkedCommunities",
      count: { $sum: 1 }
    }
  },
  {
    $project: {
      _id: 0,
      community: "$_id",
      count: "$count"
    }
  }
] )
试试看,如果您有任何问题,请告诉我。

这里也许可以帮助您

users.aggregate([
{
    $lookup:
        {
            from: "Community",
            localField: "linkedCommunities",
            foreignField: "_id",
            as: "linkedcommunities"
        }}
,{
    $unwind: "$linkedCommunities"
},
{
    $group : {
        _id : "$linkedCommunities",
        count: { $sum: 1 }
    }
},
{
    $project: {
        _id: 0,
        community: "$_id",
        count: "$count"
    }
}]}

这非常适合给我计数。谢谢现在我只需要弄清楚如何把这一切联系起来。