【问题标题】:MongoDB Aggregate, Project and MatchMongoDB 聚合、项目和匹配
【发布时间】:2021-11-19 11:51:46
【问题描述】:

我设法创建了一个聚合查询来检索记录及其计数,按年份分组。

我当前的查询

db.records.aggregate([
        {"$project": {"_id": 0, "date": {"$dateFromString": {"format": "%Y-%m-%d", "dateString": "$when"}}}},
        {"$group": {"_id": {"$year": "$date"}, "count": {"$sum": 1}}},
        {"$sort": {"_id": 1}}
])

我的收藏

{
    "id": "123456", 
    "when": "2021-01-01"

}

如何更改当前查询以检索给定年份的所有记录及其计数并按月分组?

样本输出

[{'_id': 01, 'count': 15}, {'_id': 02, 'count': 53}, {'_id': 03, 'count': 64}, {'_id': 04, 'count': 44}, {'_id': 05, 'count': 42}, {'_id': 06, 'count': 129}, {'_id': 07, 'count': 170}, {'_id': 08, 'count': 148}, {'_id': 09, 'count': 67}, {'_id': 10, 'count': 67}, {'_id': 11, 'count': 67}, {'_id': 12, 'count': 50}]

【问题讨论】:

    标签: python mongodb mongodb-query


    【解决方案1】:

    你实际上是在正确的轨道上。将日期字符串转换为日期后,只需使用$year进行过滤,并使用$group中的$month进行分组和计数。

    db.collection.aggregate([
      {
        "$project": {
          "_id": 0,
          "date": {
            "$dateFromString": {
              "format": "%Y-%m-%d",
              "dateString": "$when"
            }
          }
        }
      },
      {
        "$match": {
          $expr: {
            $eq: [
              {
                "$year": "$date"
              },
              2021
            ]
          }
        }
      },
      {
        $group: {
          _id: {
            $month: "$date"
          },
          count: {
            $sum: 1
          }
        }
      }
    ])
    

    这是Mongo playground 供您参考。

    附注:将日期存储为字符串被认为是反模式,会使您的查询变得不必要地复杂。建议将它们存储为适当的日期字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-09
      • 2020-07-30
      • 2020-06-29
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      • 1970-01-01
      相关资源
      最近更新 更多