1 0
Read Time:2 Minute, 2 Second

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

MongoDB Relations

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

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.

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Comment

Verified by MonsterInsights