Concept of Relationships and Database References in MongoDB

Last updated on May 30 2022
Satyen Sahu

Table of Contents

Concept of Relationships and Database References in MongoDB

MongoDB – Relationships

Relationships in MongoDB represent how various documents are logically associated with one another. Relationships are often modeled via Embedded and Referenced approaches. Such relationships are often either 1:1, 1:N, N:1 or N:N.
Let us consider the case of storing addresses for users. So, one user can have multiple addresses making this a 1:N relationship.
Subsequent is that the sample document structure of user document −
{
“_id”:ObjectId(“52ffc33cd85242f436000001”),
“name”: “Tom Hanks”,
“contact”: “987654321”,
“dob”: “01-01-1991”
}
Subsequent is that the sample document structure of address document −
{
“_id”:ObjectId(“52ffc4a5d85242602e000000”),
“building”: “22 A, Indiana Apt”,
“pincode”: 123456,
“city”: “Los Angeles”,
“state”: “California”
}

Modeling Embedded Relationships

In the embedded approach, we’ll embed the address document inside the user document.
{
“_id”:ObjectId(“52ffc33cd85242f436000001”),
“contact”: “987654321”,
“dob”: “01-01-1991”,
“name”: “Tom Benzamin”,
“address”: [
{
“building”: “22 A, Indiana Apt”,
“pincode”: 123456,
“city”: “Los Angeles”,
“state”: “California”
},
{
“building”: “170 A, Acropolis Apt”,
“pincode”: 456789,
“city”: “Chicago”,
“state”: “Illinois”
}
]
}
This approach maintains all the related data during a single document, which makes it easy to retrieve and maintain. The entire document are often retrieved in a single query like −
>db.users.findOne({“name”:”Tom Benzamin”},{“address”:1})
Note that in the above query, db and users are the database and collection respectively.
The drawback is that if the embedded document keeps on growing too much in size, it can impact the read/write performance.

Modeling Referenced Relationships

This is the approach of designing normalized relationship. In this approach, both the user and address documents will be maintained separately but the user document will contain a field that will reference the address document’s id field.
{
“_id”:ObjectId(“52ffc33cd85242f436000001”),
“contact”: “987654321”,
“dob”: “01-01-1991”,
“name”: “Tom Benzamin”,
“address_ids”: [
ObjectId(“52ffc4a5d85242602e000000”),
ObjectId(“52ffc4a5d85242602e000001”)
]
}
As shown above, the user document contains the array field address_ids which contains ObjectIds of corresponding addresses. Using these ObjectIds, we will query the address documents and obtain address details from there. With this approach, we’ll need two queries: first to fetch the address_ids fields from user document and second to fetch these addresses from address collection.
>var result = db.users.findOne({“name”:”Tom Benzamin”},{“address_ids”:1})
>var addresses = db.address.find({“_id”:{“$in”:result[“address_ids”]}})

MongoDB – Database References

As seen within the last section of MongoDB relationships, to implement a normalized database structure in MongoDB, we use the concept of Referenced Relationships also referred to as Manual References during which we manually store the referenced document’s id inside other document. However, in cases where a document contains references from different collections, we will use MongoDB DBRefs.

DBRefs vs Manual References

As an example scenario, where we might use DBRefs rather than manual references, consider a database where we are storing different types of addresses (home, office, mailing, etc.) in several collections (address_home, address_office, address_mailing, etc). Now, when a user collection’s document references an address, it also needs to specify which collection to seem into supported on the address type. In such scenarios where a document references documents from many collections, we should always use DBRefs.

Using DBRefs

There are three fields in DBRefs −
• $ref − This field specifies the gathering of the referenced document
• $id − This field specifies the _id field of the referenced document
• $db − This is often optional field and contains the name of the database during which the referenced document lies
Consider a sample user document having DBRef field address as shown in the code snippet −
{
“_id”:ObjectId(“53402597d852426020000002”),
“address”: {
“$ref”: “address_home”,
“$id”: ObjectId(“534009e4d852427820000002”),
“$db”: “tecklearn”},
“contact”: “987654321”,
“dob”: “01-01-1991”,
“name”: “Tom Benzamin”
}
The address DBRef field here specifies that the referenced address document lies in address_home collection under tecklearn database and has an id of 534009e4d852427820000002.
The subsequent code dynamically looks in the collection specified by $ref parameter (address_home in our case) for a document with id as specified by $id parameter in DBRef.
>var user = db.users.findOne({“name”:”Tom Benzamin”})
>var dbRef = user.address
>db[dbRef.$ref].findOne({“_id”:(dbRef.$id)})
The above code returns the subsequent address document present in address_home collection −
{
“_id” : ObjectId(“534009e4d852427820000002”),
“building” : “22 A, Indiana Apt”,
“pincode” : 123456,
“city” : “Los Angeles”,
“state” : “California”
}

So, this brings us to the end of blog. This Tecklearn ‘Concept of Relationships and Database References in MongoDB’ helps you with commonly asked questions if you are looking out for a job in MongoDB and No-SQL Database Domain.
If you wish to learn and build a career in MongoDB or No-SQL Database domain, then check out our interactive, MongoDB Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

MongoDB Training

MongoDB Training

About the Course

Tecklearn’s MongoDB Training helps you to master the NoSQL database. The course makes you job-ready by letting you comprehend schema design, data modelling, replication, and query with MongoDB through real-time examples. Along with this, you’ll also gain hands-on expertise in installing, configuring, and maintaining the MongoDB environment, including monitoring and operational strategies from this online MongoDB training. Upon completion of this online training, you will hold a solid understanding and hands-on experience with MongoDB.

Why Should you take MongoDB Training?

• MongoDB – a $36 billion to a $40 billion market growing at 8% to 9% annually – Forbes.com
• Average salary of a Mongo DB certified professional is $134k – Indeed.com
• MongoDB has more than 900 customers, including 27 Fortune 100 companies like Cisco, eBay, eHarmony, MetLife & Salesforce.com

What you will Learn in this Course?

Introduction to MongoDB and Importance of NoSQL
• Understanding the basic concepts of RDBMS
• What is NoSQL Database and its significance?
• Challenges of RDBMS and How NoSQL suits Big Data needs
• Types of NoSQL Database and NoSQL vs. SQL Comparison
• CAP Theorem and Implementing NoSQL
• Introduction to MongoDB and its advantages
• Design Goals for MongoDB Server and Database, MongoDB tools
• Collection, Documents and Key Value Pair
• Introduction to JSON and BSON documents
• MongoDB installation
MongoDB Installation
• MongoDB Installation
• Basic MongoDB commands and operations,
• Mongo Chef (MongoGUI) Installation
Schema Design and Data Modelling
• Why Data Modelling?
• Data Modelling Approach
• Data Modelling Concepts
• Difference between MongoDB and RDBMS modelling
• Challenges for Data Modelling
• Model Relationships between Documents
• Data Model Examples and Patterns
• Model Tree Structures
CRUD Operations
• MongoDB Architecture
• CRUD Introduction and MongoDB CRUD Concepts
• MongoDB CRUD Concerns (Read and Write Operations)
• Cursor Query Optimizations and Query Behaviour in MongoDB
• Distributed Read and Write Queries
• MongoDB Datatypes
Indexing and Aggregation Framework
• Concepts of Data aggregation and types and data indexing concepts
• Introduction to Aggregation
• Approach to Aggregation
• Types of Aggregation: Pipeline, MapReduce and Single Purpose
• Performance Tuning
MongoDB Administration
• Administration concepts in MongoDB
• MongoDB Administration activities: Health check, recovery, backup, database sharing and profiling, performance tuning etc.
• Backup and Recovery Methods for MongoDB
• Export and Import of Data from MongoDB
• Run time configuration of MongoDB
MongoDB Security
• Security Introduction
• MongoDB security Concepts and security approach
• MongoDB integration with Java and Robomongo
Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Concept of Relationships and Database References in MongoDB"

Leave a Message

Your email address will not be published. Required fields are marked *