Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • MongoDB - Get Started
  • What is MongoDB?
  • Install MongoDB
  • MongoDB Server
  • MongoDB Shell
  • MongoDB Shell Commands
  • MongoDB Compass
  • MongoDB Database
  • MongoDB Collections
  • MongoDB Documents
  • Insert Single Document
  • Insert Multiple Documents
  • Import Data into Collection
  • Find Single Document
  • Find Multiple Documents
  • MongoDB Cursor
  • MongoDB Sort Documents
  • Update Single Document
  • Update Multiple Documents
  • Update Arrays
  • Update Embedded Documents
  • Delete Documents
  • Relations in MongoDB
  • Aggregation in MongoDB
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

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.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.