Site icon DataFlair

MongoDB Relationships (Embedded & Reference) – Database References

MongoDB Relationships (Embedded & Reference) - Database References

MongoDB Relationships (Embedded & Reference) - Database References

FREE Online Courses: Enroll Now, Thank us Later!

In the last tutorial, we had seen MongoDB Backup and Restore Options. Now, we will be looking at MongoDB relationships and database reference. In which, we will learn teo different methods of relationship in MongoDB: Embedded and Documented Reference.

So, let’s start MongoDB Relationships Tutorial.

Methods to Create MongoDB Relationships

To create a MongoDB relationships, we have to either embed a BSON document within another or reference it from another. In MongoDB, you can create a relationship using the following methods:

  1. Embedded Relationships
  2. Documented Reference Relationships

i. Embedded Relationships in MongoDB

The benefit of using the above method is performed. If it will be embedded within the documents, queries will run faster than if we spread them on multiple documents. This will provide acceleration in the performance, especially with a large amount of data.

Here, in embedded relationships, we will discuss two types of model:

a. One to One Relationship in MongoDB

It is where the parent document has one child, and the child has one parent. With the help of an example, we will learn about this one to one relationship.

db.singers.insert(
  {
     _id : 2,
     artistname : "XYZ",
     address : {
                  street : "Apollo Street",
                  city : "Mumbai",
                  state : "Maharashtra",
                  country : "India"
                }
    }
)

After executing the following command we will get the following output:

WriteResult({ “nInserted” : 1 })

b. One to Many Relationships in MongoDB

It is a MongoDB relationship, in which a parent can have many child documents in it. But child document can have only one parent. We will take an example to understand the following relationship.

db.singers.insert(
  {
     _id : 3,
     artistname : "XYZ",
     albums : [
             {
               album : "DEF",
               year : 2000,
               genre : "Blues"
               }, 
               {
                    album : "ABC",
                    year : 2013,
                    genre : "Classical Music"
               }
          ]
     }
)

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

After executing the following code, we will get the following result:

WriteResult({ “nInserted” : 1 })

ii. Document Referenced Relationships in MongoDB

Rather than implanting a child document into the parent document, we separate the child and parent document respectively. When data needs to be repeated across many documents, it is helpful to have them in their own separate document.

This reduces error and keeps data consistent. We will take an example to understand this relationship in a better manner.

a. Parent Document

db.singers.insert(
  {
    _id : 4,
    artistname : "UVW"
   }
)

b. Child Documents

Here we will add 3 documents.

db.instruments.insert(
{
    _id : 9,
    singer_name : "GHI",
    instrument : [ "Accordion", "Jaw Harps", "Keyboards" ],
    artist_id : 4
  }
)

db.instruments.insert(
  {
    _id : 10,
    name : "ABC",
    instrument : [ "Banjo", "Cello" ],
    artist_id : 4
  }
)

db.instruments.insert(
 {
    _id : 11,
    name : "LMN",
    instrument : "Membranophones",
    artist_id : 4
  }
)

c. Querying the MongoDB Relationships

After inserting these documents now we will use $lookup to perform left outer join on the two collections.

Here, we will use aggregate() method and $match, so that we get the details of artist, and we get the child and parent documents together.

db.singers.aggregate([
  {
     $lookup:
       {
         from: "instruments",
         localField: "_id",
         foreignField: "artist_id",
         as: "band_members"
       }
        },
        { $match : { artistname : "UVW" } }
]).pretty()

After executing the code we will get the following output:

{
“_id” : 4,
“artistname” : “UVW”,
“band_members” : [
{
“_id” : 9,
“singer_name” : “GHI”,
“instrument” : [ “Accordion”, “Jaw Harps”, “Keyboards” ],
“artist_id” : 4
},
{
“_id” : 10,
name : “ABC”,
instrument : [ “Banjo”, “Cello” ],
artist_id : 4
},
{
“_id” : 11,
“name” : “LMN”,
“instrument” : “Membranophones”,
“artist_id” : 4
}
]
}

We can see that 2 fields are from singers collection and rest are from instruments collection.

MongoDb Database References

If in some cases our documents contain references from different collection then we have to use database reference at that time. It is also called as DBRefs. The reason why we are using this is that manual references do not convey the database and collection names.

DBRefs are used to represent a document rather than a specific reference type. They include collection name, value from _id field and in some cases database name.

The fields related to DBRefs are as follows:

We will take an example to understand the following fields:

{ "$ref" : <value>, "$id" : <value>, "$db" : <value> }

Consider a document from the collection that stored a DBRef in an example field:

{
"_id" : ObjectId("5126bbf64aed4daf9e2ab771"),
// .. application fields
"example" : {
          "$ref" : "creators",
          "$id" : ObjectId("5126bc054aed4daf9e2ab772"),
          "$db" : "users"
          }
}

i. List of Drivers Supported by DBRefs

Now we will take a look at the list of drivers supported by DBRefs:

So, this was all about MongoDB Relationships and Database Reference. Hope, you liked our explanation.

Summary

Hence, we have studied MongoDB relationships and database reference. In addition, we have see two different methods to create relationships. At last, we discussed a list of drivers supported by DBRefs.

Still, if you find any query, feel free to ask in the comment box.

Exit mobile version