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 calledusers
in the current database. -
db.users.insert({ name: "John Doe", groups: [] })
: This inserts a document into theusers
collection with the nameJohn Doe
and an emptygroups
array. -
db.groups.insert({ name: "Group A", users: [] })
: This inserts a document into thegroups
collection with the nameGroup A
and an emptyusers
array. -
db.groups.update({ name: "Group A" }, { $push: { users: { $ref: "users", $id: ObjectId("5f3f9f9f9f9f9f9f9f9f9f9f") } } })
: This updates thegroups
collection by pushing a reference to theusers
collection with the_id
of the user document to theusers
array in theGroup A
document. -
db.users.update({ name: "John Doe" }, { $push: { groups: { $ref: "groups", $id: ObjectId("5f3f9f9f9f9f9f9f9f9f9f9f") } } })
: This updates theusers
collection by pushing a reference to thegroups
collection with the_id
of the group document to thegroups
array in theJohn Doe
document.
Helpful links
More of Mongodb
- How to work with time series data in MongoDB?
- How to use watch in MongoDB?
- How to check the version of MongoDB?
- How to update many documents in MongoDB?
- How to use triggers in MongoDB?
- How to remove a field from MongoDB?
- How to use MongoDB queue?
- How to use unwind in MongoDB?
- How to list MongoDB users?
- How to query with "not in" condition in MongoDB?
See more codes...