本文介绍了MongoDB 添加以变量值命名的新字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,鉴于很少有这样的文件

My question is, given few documents like this one

{
  deliveryDay: "2021-01-14",
  plate: {
    name: "pasta",
    quantity: 1
  }
}

{
  deliveryDay: "2021-01-16",
  plate: {
    name: "pasta",
    quantity: 3
  }
}

{
  deliveryDay: "2021-01-16",
  plate: {
    name: "pizza",
    quantity: 2
  }
}


有没有办法获得下面想要的结果?我尝试使用 $addFields 自定义命名字段,就像这样 {"$deliveryDay": "$plate.quantity"} 但给了我无效的错误.聚合不是问题,我在聚合框架中,所以我需要使用聚合管道阶段来完成.

There's a way to obtain the wanted result below? I tried to have a custom named field with $addFields like this {"$deliveryDay": "$plate.quantity" } but gives me invalid error. The aggregation is not a problem to do and I'm inside the aggregation-framework so I need to do it using aggregation pipeline stages.

参加结果:

{
  "2021-01-14": 1,
  "2021-01-16": 3,
  plate: {
    name: "pasta"
  }
}

{
  "2021-01-14": 0,
  "2021-01-16": 2,
  plate: {
    name: "pizza"
  }
}

推荐答案

所以思路是:

  1. deliveryDayplate.name对文档进行分组,得到plate.quantity的总和.
  2. 再次按 name 将上述结果分组以生成 [{ k: "", v: "";}] 格式.
  3. 连接 { k: "plate", v: { name: "$_id";} } 到上面的数组中.
  4. 现在使用 array 转换为对象$arrayToObject.
  1. Group the documents by deliveryDay and plate.name to get the sum of plate.quantity.
  2. Group above result again by name to generate an array of [{ k: "", v: "" }] format.
  3. Concatenate { k: "plate", v: { name: "$_id" } } into the above array.
  4. Now convert the array into object using $arrayToObject.

Mongo 游乐场的解决方案.试试这个:

db.testCollection.aggregate([
    {
        $group: {
            _id: {
                dDate: "$deliveryDay",
                name: "$plate.name"
            },
            sumOfQty: { $sum: "$plate.quantity" }
        }
    },
    {
        $group: {
            _id: "$_id.name",
            array: {
                $push: {
                    k: "$_id.dDate",
                    v: "$sumOfQty"
                }
            }
        }
    },
    {
        $addFields: {
            array: {
                $concatArrays: ["$array", [{ k: "plate", v: { name: "$_id" } }]]
            }
        }
    },
    {
        $replaceRoot: {
            newRoot: { $arrayToObject: "$array" }
        }
    }
]);

输出

/* 1 */
{
    "2021-01-16" : 2,
    "plate" : {
        "name" : "pizza"
    }
},

/* 2 */
{
    "2021-01-14" : 1,
    "2021-01-16" : 3,
    "plate" : {
        "name" : "pasta"
    }
}

这篇关于MongoDB 添加以变量值命名的新字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 08:39