【问题标题】:Mongoose group and count by item in array猫鼬组并按数组中的项目计数
【发布时间】:2021-11-21 23:34:08
【问题描述】:

下面是我的mongodb结构:

[{
    countries: ["US"],
    type: "4"
  },
  {
    countries: ["IN"],
    type: "4"
  },
  {
    countries: ["US"],
    type: "4"
  }
]

注意:countries 在这种情况下,数组中只有一项

我希望对type === 4 的位置进行分组和计数,以便结果为:

[{
    countries: ["US"],
    count: 2
},{
    countries: ["IN"],
    count: 1
}]

好吧,我尝试过像这样使用聚合,但我想我弄错了:

const aggregatorOpts = [{
  $group: {
    _id: "$countries",
    count: { $sum: 1 }
  }
}]

Model.aggregate(aggregatorOpts).exec()

任何有关如何进行聚合的帮助可能都会受到赞赏。

提前致谢!

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    这是你想要的吗?你需要先做一个 $match 。 https://mongoplayground.net/p/UuOF53E44tG

    db.collection.aggregate([
      {
        $match: {
          type: {
            $eq: "4"
          }
        }
      },
      {
        $group: {
          _id: "$countries",
          count: {
            $sum: 1
          }
        }
      }
    ])
    

    【讨论】:

    • 谢谢!它现在工作正常
    猜你喜欢
    • 2021-06-15
    • 2017-06-07
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 2019-11-30
    相关资源
    最近更新 更多