How to use MongoDB graphLookup for a Recursive Query of Nested Documents?



Hey Developers❤, I understand that performing recursion in MongoDB to get a tree-like structure or you can say MongoDB graph database structure can be challenging, especially with complex collections and schemas. 

I am also a software developer, and I must say I had real pain when I was implementing this in a real project, which had a terrifically complex collection structure.

There might be some exceptionally intricate search queries you need to execute with such complex structures. 

However, I'll simplify the process for you with this beginner's tutorial on `$graphLookup`. After this, you'll never feel exhausted while performing your tasks.

How Does MongoDB graphLookup Look like?


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


How to use MongoDB graphLookup to fetch Tree Structure Data

Take your MongoDB Schemas

Suppose I have these two collections:

One is "users" and other one is "Friends".


This one is Users Collection.


This one is FriendShip Collection. Now you want these two get merged into one. Right?


Each document in the above users collection contains a name and a _id, containing user information.
User friendships are represented by the friendships collection. Every document has two unique IDs: friend_id, which identifies the user who accepted them, and user_id, which identifies the user who initiated the friendship.

What are the Cases?

There are two cases to use MongoDB as a Graph database.

1. Within the collection

2. Across collections

Case1. Within the Collection (Self-referencing)

This is the point at which documents that are part of the same collection make reference to one another. Finding friends of friends within the friends collection would be this in our situation.


db.friendships.aggregate([
   {
     $graphLookup: {
       from: "friendships",
       startWith: "$friend_id",
       connectFromField: "friend_id",
       connectToField: "user_id",
       as: "friendshipTree"
     }
   },
   {
     $project: {
       _id: 0,
       user_id: 1,
       friends: "$friendshipTree.user_id"
     }
   }
 ])

 


Case 2. Across Collections:

Documents from one collection can reference documents from another collection in this way. In our scenario, it would include searching through the user and friends collections for users and their friends.


db.users.aggregate([
   {
     $graphLookup: {
       from: "friendships",
       startWith: "$_id",
       connectFromField: "_id",
       connectToField: "user_id",
       as: "friendshipTree",
       maxDepth: 1
     }
   },
   {
     $project: {
       _id: 0,
       name: 1,
       friends: "$friendshipTree.friend_id"
     }
   }
 ])
 


Happy Coding✌

Frequently Asked Questions

1. What is the limit of graphLookup in MongoDB?

The memory allotted to the $graphLookup is 100 megabytes. If the aggregate() pipeline has allowDiskUse: true given, the $graphLookup stage will ignore the option.

2. Can MongoDB be used as a graph database?

MongoDB Can Be Used as a Graph Database, Yes!

3. How to use graphLookup in MongoDB?

Follow my steps to get your desired tree structure data using MongoDB graphLookup .

4. How to use the result of $graphLookup in $match stage?

You can use the $graphLookup result in the $match stage of the MongoDB aggregation pipeline by simply referencing the field in the following stages that contain the $graphLookup result.

5. How to use Graphlookup to fetch a tree structure data?

This blog tutorial has demonstrated in a simple way to to use Graphlookup to fetch tree structure data.

codegirl

Hello! I'm a Developer with a strong passion for coding and writing. My expertise lies in creating scalable web applications using leading-edge technologies. I am proficient in various programming languages, including Java, SQL, Mongodb, Express Js, Node JS, React Js and Next.js. Beyond coding, I shine in the world of technical content writing, using my knowledge to create engaging and informative articles.

Post a Comment

Previous Post Next Post