How to get value of array based on id from same collection in mongodb

Viewed 37

How to get value of array based on id from same collection in mongodb . Here "linkedBy" is array of "storyId". So in result in "linkedBy" array instead of only "storyId" need to fetch all details of that "storyId".

collection 1:-

{
 "_id" : ObjectId("6130f4f16dc8c60fa554c37e"),
    "storyId" : "101",
    "storyTitle" : "story 1",
    "storyPriority" : "",
    "storyPoints" : "0",
    "linkedBy" : [],
},
{
 "_id" : ObjectId("2345f4f16dc8c60fa554c37e"),
    "storyId" : "102",
    "storyTitle" : "story 2",
    "storyPriority" : "",
    "storyPoints" : "0",
    "linkedBy" : [101],
}
    

expected result :-

{
 "_id" : ObjectId("6130f4f16dc8c60fa554c37e"),
    "storyId" : "101",
    "storyTitle" : "story 1",
    "storyPriority" : "",
    "storyPoints" : "0",
    "linkedBy" : [],
},
{
 "_id" : ObjectId("2345f4f16dc8c60fa554c37e"),
    "storyId" : "102",
    "storyTitle" : "story 2",
    "storyPriority" : "",
    "storyPoints" : "0",
    "linkedBy" : [
      {
        "_id" : ObjectId("6130f4f16dc8c60fa554c37e"),
        "storyId" : "101",
        "storyTitle" : "story 1",
        "storyPriority" : "",
        "storyPoints" : "0",
        "linkedBy" : [],
      }
    ],
}
1 Answers

Having "storyId" and "linkedBy" values be different types is a bit unfortunate, but not insurmountable. It's also not clear how you want to handle possible circular references and/or recursion depth.

Anyway, here's one way to generate your desired output (as I understand it) using "$graphLookup".

db.collection.aggregate([
  {
    "$graphLookup": {
      "from": "collection",
      "startWith": {
        "$map": {
          "input": "$linkedBy",
          "as": "storyIdInt",
          "in": {
            "$toString": "$$storyIdInt"
          }
        }
      },
      "connectFromField": "linkedBy",
      "connectToField": "storyId",
      "as": "linkedBy",
      "maxDepth": 0
    }
  }
])

Try it on mongoplayground.net.

Related