mongodb map data in one collection

Viewed 41

My intention is to map the reference column based on the id. This is my data in one collection.

[{
  "title": "A",
  "reference": ["2"],
  "id": "1",
  "author": ["Doraemon"]
},{
  "title": "B",
  "reference": [],
  "id": "2",
  "author": ["Naruto"]
}]

Does anyone can help me how to make it like this

[{
  "title": "A",
  "reference": ["B"],
  "id": "1",
  "author": ["Doraemon"]
},{
  "title": "B",
  "reference": [],
  "id": "2",
  "author": ["Naruto"]
}]
1 Answers

You can do self lookup

db.collection.aggregate([
  {
    "$lookup": {
      "from": "collection",
      "localField": "reference",
      "foreignField": "id",
      "as": "selfJoin"
    }
  },
  {
    $addFields: {
      reference: "$selfJoin.title"
    }
  },
  {
    $project: {
      selfJoin: 0
    }
  }
])

Working Mongo playground

Related