5

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
}
Ayoub k
  • 7,788
  • 9
  • 34
  • 57

1 Answers1

7

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"
  }}
])
Ashh
  • 44,693
  • 14
  • 105
  • 132
  • thank you, it works. is there any solution for the older version like mongodb 2.2 ? – Ayoub k Feb 10 '19 at 14:23
  • Yes can be done using some javascript tricks but the `$lookup` was introduced in 3.2 and above and the good way to do. – Ashh Feb 10 '19 at 14:26