Suraj Dalvi
Suraj Dalvi

Reputation: 1078

Mongo Graph Lookup Query

My mongo collection name is home and whose having the following documents in it.

[{

    "title": "Java",
    "uid": "1",
    "_metadata": {
        "references": [{
            "asssetuid": 10
        }]
    }
},
{

    "title": "Servlet",
    "uid": "2",
    "_metadata": {
        "references": [{
                "uid": "1"
            },
            {
                "asssetuid": 11
            }
        ]
    }
},
{

    "title": "JSP",
    "uid": "3",
    "_metadata": {
        "references": [{
            "uid": "2"
        }]
    }
}

]

I want results like

{
"uid": 1,
"_metadata": {
    "references": [{
            "asssetuid": 10
        }, {
            "uid": "2"
        },
        {
            "asssetuid": 11
        },
        {
            "uid": "3"
        }
    ]
}

}

as per we need full hierarch of a document whose uid is 1.

How we can get this result. is any way in graph lookup query to get the required result.

Upvotes: 1

Views: 288

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

You want to use $graphLookup, it gives you the power to recursively search for matches which is what you're looking for:

db.home.aggregate([
  {
    $match: {
      uid: "1"
    }
  },
  {
    "$graphLookup": {
      "from": "home",
      "startWith": "$uid",
      "connectFromField": "uid",
      "connectToField": "_metadata.references.uid",
      "as": "matches"
    }
  },
  {
    $project: {
      uid: 1,
      _metadata: {
        refrences: {
          $map: {
            input: "$matches",
            as: "match",
            in: {
              uid: "$$match.uid"
            }
          }
        }
      }
    }
  }
])

Mongo Playground

Upvotes: 1

Related Questions