Reputation: 209
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
Reputation: 4452
So the idea is:
deliveryDay
and plate.name
to get the sum of plate.quantity
.name
to generate an array of [{ k: "", v: "" }]
format.{ k: "plate", v: { name: "$_id" } }
into the above array.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