mongodbHow to create a many to many relation in MongoDB?
MongoDB supports many-to-many relationships through the use of embedded documents and document references. To create a many-to-many relationship in MongoDB, we need to create two collections, one for each entity in the relationship. For example, if we have a users collection and a groups collection, we can create a many-to-many relationship between them by embedding a groups array in each user document and a users array in each group document.
Example code
// Create users collection
db.createCollection("users")
// Create groups collection
db.createCollection("groups")
// Insert a user
db.users.insert({
name: "John Doe",
groups: []
})
// Insert a group
db.groups.insert({
name: "Group A",
users: []
})
// Add user to group
db.groups.update(
{ name: "Group A" },
{ $push: { users: { $ref: "users", $id: ObjectId("5f3f9f9f9f9f9f9f9f9f9f9f") } } }
)
// Add group to user
db.users.update(
{ name: "John Doe" },
{ $push: { groups: { $ref: "groups", $id: ObjectId("5f3f9f9f9f9f9f9f9f9f9f9f") } } }
)
Output example
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Code explanation
-
db.createCollection("users"): This creates a collection calledusersin the current database. -
db.users.insert({ name: "John Doe", groups: [] }): This inserts a document into theuserscollection with the nameJohn Doeand an emptygroupsarray. -
db.groups.insert({ name: "Group A", users: [] }): This inserts a document into thegroupscollection with the nameGroup Aand an emptyusersarray. -
db.groups.update({ name: "Group A" }, { $push: { users: { $ref: "users", $id: ObjectId("5f3f9f9f9f9f9f9f9f9f9f9f") } } }): This updates thegroupscollection by pushing a reference to theuserscollection with the_idof the user document to theusersarray in theGroup Adocument. -
db.users.update({ name: "John Doe" }, { $push: { groups: { $ref: "groups", $id: ObjectId("5f3f9f9f9f9f9f9f9f9f9f9f") } } }): This updates theuserscollection by pushing a reference to thegroupscollection with the_idof the group document to thegroupsarray in theJohn Doedocument.
Helpful links
More of Mongodb
- How to use transactions in MongoDB?
- How to empty an array in MongoDB?
- How to use watch in MongoDB?
- How to use MongoDB queue?
- How to use unwind in MongoDB?
- How to use MongoDB pull?
- How to use triggers in MongoDB?
- How to rename a field in MongoDB?
- What is MongoDB default port?
- How to check if array is empty in MongoDB?
See more codes...