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

In RDBMS databases like SQL Server, relationships between the tables can be one-to-one, one-to-many, and many-to-many.

In MongoDB, one-to-one, one-to-many, and many-to-many relations can be implemented in two ways:

  1. Using embedded documents
  2. Using the reference of documents of another collection

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.

Example: Relation using Embedded Document
db.employee.insertOne({
     _id: ObjectId("32521df3f4948bd2f54218"),
    firstName: "John",
    lastName: "King",
    email: "[email protected]",
    salary: "33000",
    DoB: new Date('Mar 24, 2011'),
    address: { 
                street:"Upper Street",
                house:"No 1",
                city:"New York",
                country:"USA"
            }
})

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.

Example: Implement One-to-One Relation using Reference
db.address.insertOne({
     _id: 101,
    street:"Upper Street",
    house:"No 1",
    city:"New York",
    country:"USA"
})

db.employee.insertOne({
    firstName: "John",
    lastName: "King",
    email: "[email protected]",
    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.

Example: Find Related Documents
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.

Example: $lookup to Get Related Documents
db.employee.aggregate([{$lookup:{from:'address',localField:'address',foreignField:"_id",as:'addr'}}])
Output
[
  {
    _id: ObjectId("617a75c013dceca5c350d52f"),
    firstName: 'John',
    lastName: 'King',
    email: '[email protected]',
    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.

Want to check how much you know MongoDB?