Home > OS >  how to join two collections with array object field in mongodb
how to join two collections with array object field in mongodb

Time:03-23

I'm new in MongoDB. I have two collections with names adverb and categories. adverb fields are

{
    "advId": "myid",
    "advTitle": "myTitle",
    "advDescription": "test description",
    "fromUser": "userid",
    "subCategoryId": "catid",
    "advLabel": "1",
    "cityId": "cityid",
    "areaName": "areaName",
    "chatState": true,
    "geoPosition": {
        "latitude": 21.61980691353274,
        "longitude": 51.519725019871956
    },
    "advImages": [],
    "timeStamp": 1646670847761,
    "visibility": false
}

and categories collection with fields

{
    "catId": "catId",
    "catTitle": "catTitle",
    "catSub": [{
        "subId": "subId",
        "subTitle": "آپارتمان"
    }, {
        "subId": "subId",
        "subTitle": "ویلایی"
    }]
}

and I want to join "adverb's subCategoryId" with "subId on catSub's categories collection" that catSub is an array with object values How can I do this? tnx.

CodePudding user response:

db.adverb.aggregate([
  {
    "$lookup": {
      "from": "categories",
      "localField": "subCategoryId",
      "foreignField": "catSub.subId",
      "as": "docs"
    }
  }
])

mongoplayground

  • Related