Relations in MongoDB: One-to-One, One-to-Many, Many-to-Many

In MongoDB, one-to-one, one-to-many, and many-to-many relations can be implemented in two ways:
- Using embedded documents
- Using the reference of documents of another collection
1. Implement Relation using Embedded Document
You can include related data as embedded documents. For example, you can include an address as an embedded document, as shown below.
db.employee.insertOne({ _id: ObjectId("32521df3f4948bd2f54218"), firstName: "John", lastName: "King", email: "john.king@abc.com", salary: "33000", DoB: new Date('Mar 24, 2011'), address: { street:"Upper Street", house:"No 1", city:"New York", country:"USA" } })
2. Implement Relation using Reference
Another way to implement relations is by using the reference of the primary key field of documents of another collection.
For example, createĀ address
Ā collection and useĀ _id
Ā as a reference of a document in theĀ employee
Ā collection.
db.address.insertOne({ _id: 101, street:"Upper Street", house:"No 1", city:"New York", country:"USA" }) db.employee.insertOne({ firstName: "John", lastName: "King", email: "john.king@abc.com", salary: "33000", DoB: new Date('Mar 24, 2011'), address: 101 })
In the above example, the relation between employee
and address
collection is implemented using the reference ids. A document in the employee
collection contains an address
field that has a value of an existing _id
in the address
collection. It forms one-to-one relations.
Note: You can reference any field for the relation, but it is recommended to use the unique primary key field to avoid errors.
You can retrieve related data in two steps. The following retrieves the address of an employee.
var addrId = db.employee.findOne({firstName:'John'}).address; db.address.findOne({_id:addrId});
In the above example, get the addrId
field for an employee and then find the address document by using addrId.
Use the aggregation pipeline stageĀ $lookupĀ to find the related data from the collection, as shown below.
db.employee.aggregate([{$lookup:{from:'address',localField:'address',foreignField:"_id",as:'addr'}}])
Output:
[ { _id: ObjectId("617a75c013dceca5c350d52f"), firstName: 'John', lastName: 'King', email: 'john.king@abc.com', salary: '33000', DoB: ISODate("2011-03-23T18:30:00.000Z"), address: 101, addr: [ { _id: 101, street: 'Upper Street', house: 'No 1', city: 'New York', country: 'USA' } ] } ]
In the same way, you can implement one-to-many and many-to-many relations in MongoDB.
Average Rating