I have a list of objects each one, with two lists, as following:
[
{
"name": "market2",
"materialCosts": [
{
"date": "2022-02-12",
"amount": "1234.11"
},
{
"date": "2022-02-15",
"amount": "1234.11"
}
],
"laborCosts": [
{
"date": "2022-02-12",
"amount": "12.11"
},
{
"date": "2022-02-15",
"amount": "45.11"
}
]
},
{
"name": "market1",
"materialCosts": [
{
"date": "2022-02-12",
"amount": "1234.11"
},
{
"date": "2022-02-15",
"amount": "1234.11"
}
],
"laborCosts": [
{
"date": "2022-02-12",
"amount": "12.11"
},
{
"date": "2022-02-15",
"amount": "45.11"
}
]
}
]
is there any possibility to group all costs by date using mongodb aggregation framework, no matter if they are material or labor costs, to finally have the following result:
[
{
"date": "2022-02-12",
"amount": "1234.11"
},
{
"date": "2022-02-15",
"amount": "1234.11"
}
]
Query
aggregate(
[{"$project":
{"costs": {"$concatArrays": ["$materialCosts", "$laborCosts"]}}},
{"$unwind": "$costs"},
{"$group":
{"_id": "$costs.date", "sum": {"$sum": {"$toDouble": "$costs.amount"}}}}])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.