【问题标题】:How do I aggregate the number of occurrences of an ObjectID in array?如何聚合数组中 ObjectID 的出现次数?
【发布时间】:2017-10-24 02:19:35
【问题描述】:

我有两个系列; userscommunities。我的用户可以链接到许多社区,因此我将 linkedCommunities 作为 User 架构中的数组,如下所示:

const userSchema = new Schema({
  linkedCommunities: [
    {
      type: mongoose.Schema.ObjectId,
      ref: 'Community'
    }
  ]
});

在我的communities 视图中,我想显示链接到每个社区的users 的数量,因此它会显示为:

| Community   | Number of users |
| ---------   | --------------- |
| Community 1 | 45              | 
| Community 2 | 78              |
| Community 4 | 107             | 

理想情况下,当我在 Community 模型上进行查找时,我想要一个名为 linkedUserCount 之类的字段。

我确信我可以使用aggregate 以某种方式实现这一目标,但我正在努力寻找合适的管道运营商和订单。

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    这里也许可以帮助你,

    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"
        }
    }]}
    

    【讨论】:

      【解决方案2】:

      您可以使用以下 mongodb 查询来获得所需的结果:

      db.users.aggregate( [ 
        { 
          $unwind : "$linkedCommunities" 
        },
        {
          $group : {
            _id : "$linkedCommunities",
            count: { $sum: 1 }
          }
        },
        {
          $project: {
            _id: 0,
            community: "$_id",
            count: "$count"
          }
        }
      ] )
      

      试一试,如果您有任何问题,请告诉我。

      【讨论】:

      • 这非常适合给我计数。谢谢。现在我只需要弄清楚如何将它们全部连接起来。 ?
      猜你喜欢
      • 2019-09-18
      • 2019-02-22
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      • 1970-01-01
      • 2022-12-13
      • 2020-06-04
      相关资源
      最近更新 更多