I have two collections initiatives
and resources
:
initiative document example:
{
"_id" : ObjectId("5b101caddcab7850a4ba32eb"),
"name" : "AI4CSR",
"ressources" : [
{
"function" : ObjectId("5c3ddf072430c46dacd75dbb"),
"participating" : 0.1,
},
{
"function" : ObjectId("5c3ddf072430c46dacd75dbc"),
"participating" : 5,
},
{
"function" : ObjectId("5c3ddf072430c46dacd75dbb"),
"participating" : 12,
},
{
"function" : ObjectId("5c3ddf072430c46dacd75dbd"),
"participating" : 2,
},
],
}
and a resource document:
{
"_id" : ObjectId("5c3ddf072430c46dacd75dbc"),
"name" : "Statistician",
"type" : "FUNC",
}
so i want to return each resource with the sum of participating is have. and to that i need to join the two collection.
db.resources.aggregate([
{
"$match": { type: "FUNC" }
},
{
"$lookup": {
"from": "initiatives",
"localField": "_id",
"foreignField": "initiatives.resources",
"as": "result"
}
},
])
but first i need to unwind the foreign field array.
example of the expected output:
{
"function" : "Data Manager"
"participation_sum": 50
}
{
"function" : "Statistician"
"participation_sum": 1.5
}
{
"function" : "Supply Manage"
"participation_sum": 0
}
You can use below aggregation with mongodb 3.6 and above
db.resources.aggregate([
{ "$match": { "type": "FUNC" } },
{ "$lookup": {
"from": "initiatives",
"let": { "id": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$in": ["$$id", "$ressources.function"] } } },
{ "$unwind": "$ressources" },
{ "$match": { "$expr": { "$eq": ["$ressources.function", "$$id"] } } },
{ "$group": {
"_id": "$ressources.function",
"participation_sum": { "$sum": "$ressources.participating" }
}}
],
"as": "result"
}}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With