Omar El Malak
Omar El Malak

Reputation: 209

MongoDB add new fields named with variable value

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
  }
}


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.

Attended result:

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

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

Upvotes: 2

Views: 845

Answers (1)

Dheemanth Bhat
Dheemanth Bhat

Reputation: 4452

So the idea is:

  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.

Solution in Mongo playground. Try this:

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" }
        }
    }
]);

Output

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

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

Upvotes: 3

Related Questions