ADD Data from 2 collection as comma seperated value

I have 2 collections as below
collection 1:

{
  CREATEDBY:"Lorraine Clarkin"
  CREATIONDATE:"03-MAR-21"
  BARCODEID:"A1429857"
  RECORDDESCRIPTION:"Putnam N1A review 10 31 2020 funds1 of 4"
  CHECKINDATE:"01-JAN-01"
  RECORDTYPE:"Assurance Workpapers"
  RECORDSTATE:"Recorded"
}

collection 2:

{
  "BARCODEID":"A1429857",
  "RECORDCONTENTS":"Signed rep letter"
},
{
  "BARCODEID":"A1429857",
  "RECORDCONTENTS":"Reference letter"
}

And I want RECORDCONTENTS from 2 nd collection to be merged with 1 collection as comma seperated like below

Final Result :

{
  CREATEDBY:"Lorraine Clarkin"
  CREATIONDATE:"03-MAR-21"
  BARCODEID:"A1429857"
  RECORDDESCRIPTION:"Putnam N1A review 10 31 2020 funds1 of 4"
  CHECKINDATE:"01-JAN-01"
  RECORDTYPE:"Assurance Workpapers"
  RECORDSTATE:"Recorded"
  "RECORDCONTENTS": ["Signed rep letter","Reference letter"]
}

can someone help

You can do it like this:

  • $lookup - to merge data from second collection to first collection
  • $map - to map merged data to its RECORDCONTENTS property
db.coll_1.aggregate([
  {
    "$lookup": {
      "from": "coll_2",
      "localField": "BARCODEID",
      "foreignField": "BARCODEID",
      "as": "RECORDCONTENTS"
    }
  },
  {
    "$set": {
      "RECORDCONTENTS": {
        "$map": {
          "input": "$RECORDCONTENTS",
          "in": "$$this.RECORDCONTENTS"
        }
      }
    }
  }
])

Working example

1 Like

Thank you,Script is working fine

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.