group with lookup's foreign field in mongodb group with lookup's foreign field in mongodb mongoose mongoose

group with lookup's foreign field in mongodb


You can try below aggregate function to achieve the result...

If you have mongodb version 3.6

db.promotion.aggregate([  // stage 1  { "$lookup": {    "from": Promotions.collection.name,    "let": { "tags": "$tags" },    "pipeline": [       { "$match": { "$expr": { "$eq": [ "$_id", "$$tags" ] } } }     ],     "as": "tags"  }},  // stage 2  { "$addFields": {     "tags": { "$arrayElemAt": [ "$tags", 0 ] }  }},  // stage 3  { "$group": {    "_id": "$tags._id",    "promotions": {        "$push": {            "fieldName1": "$fieldName1",            "fieldName2": "$fieldName2",        }    }  }} ])

If you have mongodb version prior to 3.6

db.promotion.aggregate([  { "$lookup": {    "from": Promotions.collection.name,    "localField": "tags",    "foreignField": "_id"     "as": "tags"  }},  { "$unwind": "tags" },  { "$group": {    "_id": "$tags._id",    "promotions": {        "$push": {            "fieldName1": "$fieldName1",            "fieldName2": "$fieldName2",        }    }  }} ])

Both will give similar output

{    "tag": {     "_id": "999",     "value": "Lorem Ipsum"   },   "promotions": [{      "_id": "0001",      "value": "Value of promotion Nº1"   },   {      "_id": "0002",      "value": "Value of promotion Nº2"   }   ]}}