在计算其他字段时按 mongoDB 中的日期分组

Group by date in mongoDB while counting other fields

我使用 MongoDB 仅仅一个星期,但我在实现这个结果时遇到了问题:我想按日期对我的文档进行分组,同时还要跟踪具有特定字段集的条目数到某个值。

因此,我的文档如下所示:

    {
    "_id" : ObjectId("5f3f79fc266a891167ca8f65"),
    "recipe" : "A",
    "timestamp" : ISODate("2020-08-22T09:38:36.306Z")
    }

其中配方是“A”、“B”或“C”。现在我正在使用这个 pymongo 查询按日期对文档进行分组:

mongo.db.aggregate(
    # Pipeline
    [
         # Stage 1
        {
            "$project": {
                "createdAt": {
                    "$dateToString": {
                        "format": "%Y-%m-%d",
                        "date": "$timestamp"
                    }
                },
                "progressivo": 1,
                "temperatura_fusione": 1
            }
        },
        # Stage 2
        {
            "$group": {
                "_id": {
                    "createdAt": "$createdAt"
                },
                "products": {
                    "$sum": 1
                }
            }
        },
        # Stage 3
        {
            "$project": {
                "label": "$_id.createdAt",
                "value": "$products",
                "_id": 0
            }
        }])

这给了我这样的结果:

[{"label": "2020-08-22", "value": 1}, {"label": "2020-08-15", "value": 2}, {"label": "2020-08-11", "value": 1}, {"label": "2020-08-21", "value": 5}]

我还想计算每个食谱在每个日期出现的次数。因此,例如,如果在 8 月 21 日我有 2 个带有“A”食谱的条目,3 个带有“B”食谱的条目和 0 个带有“C”食谱的条目,则所需的输出将是

{"label": "2020-08-21", "value": 5, "A": 2, "B":3, "C":0}

你有什么建议吗?

谢谢!

你可以像下面这样,你做的太棒了。之后,

  1. 在第二组中,我们只得到总价值每个食谱的价值
  2. $map用于去through/modify每个对象
  3. $arrayToObject 用于将我们通过映射(键:值对)所做的数组转换为对象
  4. $ifNull用于,有时你的数据可能没有"A""B""C"。但是如果没有预期输出的名称,您需要的值应该是 0

这是代码

[
  {
    "$project": {
      "createdAt": {
        "$dateToString": {
          "format": "%Y-%m-%d",
          "date": "$timestamp"
        }
      },
      recipe: 1,
      "progressivo": 1,
      "temperatura_fusione": 1
    }
  },
  {
    "$group": {
      "_id": {
        "createdAt": "$createdAt",
        "recipeName": "$recipe",
        
      },
      "products": {
        $sum: 1
      }
    }
  },
  {
    "$group": {
      "_id": "$_id.createdAt",
      value: {
        $sum: "$products"
      },
      recipes: {
        $push: {
          name: "$_id.recipeName",
          val: "$products"
        }
      }
    }
  },
  {
    $project: {
      "content": {
        "$arrayToObject": {
          "$map": {
            "input": "$recipes",
            "as": "el",
            "in": {
              "k": "$$el.name",
              "v": "$$el.val"
            }
          }
        }
      },
      value: 1
    }
  },
  {
    $project: {
      _id: 1,
      value: 1,
      A: {
        $ifNull: [
          "$content.A",
          0
        ]
      },
      B: {
        $ifNull: [
          "$content.B",
          0
        ]
      },
      C: {
        $ifNull: [
          "$content.C",
          0
        ]
      }
    }
  }
]

工作Mongo playground