GraphLookup in MongoDB

Posted By : Arun Kataria | 26-Feb-2018

$graphLookupthe new aggregation framework stage the recursively searches through the collection. Specialized graph databases such as the Neo4J specialize for traversing the graphs of relationships. There are many non-graph databases had been incorporating Graph Compute Engines to perform the similar tasks.  In MongoDB 3.3 release, we now have the ability to perform a simple graph traversal using $graphLookup aggregation framework function: 

{
   $graphLookup: {
      from: collection,
      startWith: expression,
      connectFromField: string,
      connectToField: string,
      as: string,
      maxDepth: number,
      depthField: string,
      restrictSearchWithMatch: document
   }
}
        

For example:-

  { _id: 1, name: 'a', friends: [2, 3] },
  { _id: 2, name: 'b', friends: [1, 3, 4] },
  { _id: 3, name: 'c', friends: [1, 3] },
  { _id: 4, name: 'd', friends: [2, 5] },
  { _id: 5, name: 'e', friends: [4] }
        

Querry to fetch the data:-

db.customers.aggregate([
  { $match: { _id: 1 } }, // Only look at 'a'
  {
    $graphLookup: {
      from: 'customers', // Use the customers collection
      startWith: '$friends', // Start looking at the document's `friends` property
      connectFromField: 'friends', // A link in the graph is represented by the friends property...
      connectToField: '_id', // ... pointing to another customer's _id property
      maxDepth: 1, // Only recurse one level deep
      as: 'connections' // Store this in the `connections` property
    }
  }
]); 

Result of this querry:-

{
    "_id" : 1,
    "name" : "a",
    "friends" : [
        2,
        3
    ],
    "connections" : [
        {
            "_id" : 4,
            "name" : "c",
            "friends" : [
                2,
                5
            ]
        },
        {
            "_id" : 1,
            "name" : "a",
            "friends" : [
                2,
                3
            ]
        },
        {
            "_id" : 3,
            "name" : "c",
            "friends" : [
                1,
                3
            ]
        },
        {
            "_id" : 2,
            "name" : "b",
            "friends" : [
                1,
                3,
                4
            ]
        }
    ]
}
    

 

About Author

Author Image
Arun Kataria

Arun has good skills in AngularJS, NodeJS, MongoDB and many more. He is highly motivated which allow him to strive for proficiency when accomplishing assigned duties. He is an excellent team operative.

Request for Proposal

Name is required

Comment is required

Sending message..