How to Implement a forward/backward relationship in Mongodb?

I am trying to implement the same type offorward/backward relationship shown in the image below in Mongodb in one single document.


Also, I want to be able to query data that would be coonected to those nodes using the relationships at any nodes.

I have tried to go through the Mongodb documentation as well as other sources (mongodb community, stackoverflow, etc…) to see what has already been done but I could not find anything comparable to my problem. Is it even possible? If so, how? If not is there any alternative way I could try to achieve this result? I have considered using multiple documents but I was puzzled on which I could query it.

Hi there!

Since there wasn’t a reply to your message, I tried to run it by our documentation bot. Here is the response I got :slight_smile:

To implement forward and backward relationships in MongoDB, you can use either embedded documents or references, depending on your application’s needs. Here’s a brief overview of both approaches:

Embedded Documents

Embedding is useful when you frequently query one entity to return data about another entity. This approach avoids the need for $lookup operations and can improve read performance.

Example:

Consider a blog application where each article has comments. You can embed comments directly within the article document:

db.articles.insertOne(   {      title: "My Favorite Vacation",      date: ISODate("2023-06-02"),      text: "We spent seven days in Italy...",      comments: [         {            name: "pedro123",            text: "Great article!"         },         {            name: "jane_doe",            text: "Thanks for sharing!"         }      ]   })

References

Using references is beneficial when you frequently update related data. This approach reduces the write workload by updating data in a single place.

Example:

For the same blog application, you can store comments in a separate collection and reference them in the articles collection:

// Article documentdb.articles.insertOne(   {      title: "My Favorite Vacation",      date: ISODate("2023-06-02"),      text: "We spent seven days in Italy...",      commentIds: [         ObjectId("60c72b2f9b1d8b3a4c8b4567"),         ObjectId("60c72b2f9b1d8b3a4c8b4568")      ]   })// Comment documentsdb.comments.insertMany([   {      _id: ObjectId("60c72b2f9b1d8b3a4c8b4567"),      name: "pedro123",      text: "Great article!"   },   {      _id: ObjectId("60c72b2f9b1d8b3a4c8b4568"),      name: "jane_doe",      text: "Thanks for sharing!"   }])

Forward and Backward Relationships

To implement forward and backward relationships, you can use a combination of embedding and referencing. For example, if you want to navigate from an article to its comments and from a comment back to its article, you can do the following:

  1. Forward Relationship (Article to Comments): Embed comment IDs in the article document.
  2. Backward Relationship (Comment to Article): Store the article ID in each comment document.

Example:

// Article document with forward relationshipdb.articles.insertOne(   {      title: "My Favorite Vacation",      date: ISODate("2023-06-02"),      text: "We spent seven days in Italy...",      commentIds: [         ObjectId("60c72b2f9b1d8b3a4c8b4567"),         ObjectId("60c72b2f9b1d8b3a4c8b4568")      ]   })// Comment documents with backward relationshipdb.comments.insertMany([   {      _id: ObjectId("60c72b2f9b1d8b3a4c8b4567"),      articleId: ObjectId("60c72b2f9b1d8b3a4c8b4569"),      name: "pedro123",      text: "Great article!"   },   {      _id: ObjectId("60c72b2f9b1d8b3a4c8b4568"),      articleId: ObjectId("60c72b2f9b1d8b3a4c8b4569"),      name: "jane_doe",      text: "Thanks for sharing!"   }])

This way, you can efficiently navigate between related data in both directions.


Related Resources


Model Relationships Between Documents
Docs

Map Schema Relationships
Docs

Model One-to-Many Relationships with Document References
Docs

Hi Megan,

Thanks for your answer, I had reached this conclusion and I used mongoDB ids as reference in a series of nested documents in one record document

1 Like