【问题标题】:MongoDB Compass Select Distinct FieldMongoDB Compass 选择不同的字段
【发布时间】:2020-06-08 17:13:29
【问题描述】:

我正在尝试在 MongoDB Compass 中为我的一个集合中的字段城市创建一个聚合管道。这是我目前所拥有的:

[{$unwind: {
  path: '$city',
  preserveNullAndEmptyArrays: true
}}, {$group: {
  _id: null,
  distinctCities: { $addToSet: '$city' }
}}]

如何添加每个城市的出现次数?我想要一个包含城市和计数的对象的数组。

【问题讨论】:

  • 我设法找到了一个解决方案,可以为我提供所需的数据。请参阅下面的答案。

标签: mongodb mongodb-query aggregation-framework mongodb-compass


【解决方案1】:

查询:

db.collection.aggregate([
    /** 
     * unwind city, if your desired response is just an array `[{city :..., count :... }]`
     * then you don't need to `preserveNullAndEmptyArrays`
     */
    {
      $unwind: "$city"
    },
    /** group on unique city's & count no.of occurrences */
    {
      $group: { _id: "$city", count: { $sum: 1 } }
    },
    /** group on all docs (without any condition) & push objects to an array */
    {
      $group: { _id: "", citiesAndCount: { $push: { city: "$_id", count: "$count" } } }
    }
  ])

测试: mongoplayground

参考: aggregation-pipeline

【讨论】:

    【解决方案2】:

    这在 MongoDB 中运行良好:

     const aggregatorOptionsCity = [
        { $match: req.query },
        {
          $group: {
            _id: '$city',
            count: { $sum: 1 },
          },
        },
      ];
    

    【讨论】:

    • 这个答案似乎与你的问题不符!!这将产生一个文档/对象数组I would like to have an array that consists of objects with city and count,如果这意味着聚合结果数组,那么问题就会产生误导!也不知道为什么你是unwinding 有问题而不是回答!如果不是第一阶段$unwind 和最后阶段$group 两者都是一样的..
    猜你喜欢
    • 2020-09-16
    • 2013-08-19
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 2019-10-15
    • 1970-01-01
    相关资源
    最近更新 更多