What MongoDB Many-to-Many Association?

In this post, we will learn What MongoDB Many-to-Many Association means nothing but two collections where any one of the documents in the first collection is related to a number of( multiple) documents in the second collection and we ca say vice versa. Where this requires a third join collection to manage the relationships between the two given collections.

Many-to-Many

Many-to-Many Association

To understand what many to many associations take an example here take two collections to let here ‘user’ and ‘group’ there are two collections where we know each group has multiple collections and for making connections we represent this relationship by a third collection named as ‘memberships’ where we had stored the existing relationships between two where the collection membership had a document that has user and used as the fields.

Here we had given the membership document to explain everything possible.

{
  _id: ObjectId(" 12345"),
  userId: ObjectId(" abc123"),
  groupId: ObjectId(" def456")
}

Here in the document given above represents the relationship between the user with ID “abc123” and the group with ID “def456”. To get to know about all the groups to which a user belongs, we can use the following aggregation pipeline

db.memberships.aggregate([
  { $match: { userId: ObjectId( "abc123") } },
  { $lookup: {
      from: "groups",
      local field: "groupId",
      foreign field: "_id",
      as: "group"
    }
  },
  { $unwind: "$group" },
  { $project: { _id: 0, "group.the name": 1 } }
])

The above pipeline has match to all the documents presented in the membership collection, there the “userId” field is equal to “abc123”, which is given already for joins with the “groups” collection based on the “groupId” field, and returns only the “name” field from the “groups” collection.

And same as the above all users (the fields present there ) which are nothing but belong to a particular group we could have a look at the pipeline given below as the example to understand and get it done in out project.

db.memberships.aggregate([
  { $match: { groupId: ObjectId(" def456") } },
  { $lookup: {
      from: "users",
      local field: "userId",
      foreign field: "_id",
      as: "user"
    }
  },
  { $unwind: "$user" },
  { $project: { _id: 0, "user.the name": 1 } }
])

Here in the above pipeline matches all the documents in the “memberships” collection where the “groupId” field is equal to “def456”, joins with the “users” collection based on the “userId” field, and returns only the “name” field from the “users” collection which is somewhat similar to that of the above collection which had done above to make group clear and in this case it user.

 

 

 

to learn more about  Many-to-Many Association  click

To learn more about MongoDB and tutorial related to it visit: MongoDB Problems And Tutorials

Leave a Comment

%d bloggers like this: