MongoDB Relationships (Embedded & Reference) – Database References

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.

MongoDB Relationships (Embedded & Reference) - Database References

MongoDB Relationships (Embedded & Reference) – Database References

1. 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:

  • One-to-one relationship
  • One-to-many relationship

Do you know How Projection in MongoDB Affects Performance?

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"
               }
          ]
     }
)

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

WriteResult({ “nInserted” : 1 })

Recommended reading – MongoDB Data Modeling with Document Structure 

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.

2. 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:

  • $ref: It holds the name of collection where the document resides.
  • $id: It contains the value of _id field in the referenced document.
  • $db: This field is optional. It contains the name of database where the document resides. There are few drivers which support $db.

Have a Look – MongoDB Limit Records and Skip() methods

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:

  • C: It does not support DBRefs. You will have to traverse manually.
  • C++ : It does not support DBRefs. You will have to traverse manually.
  • C#: It supports DBRefs by using https://api.mongodb.com/csharp/current/html/T_MongoDB_Driver_MongoDBRef.htm class and FetchDBRef and FetchDBRefAs methods.
  • Haskell: It does not support DBRefs. You will have to traverse manually.
  • Java: The https://api.mongodb.com/java/current/com/mongodb/DBRef.html class provides support for DBRefs.
  • JavaScript: The mongo shells Javascript interface provides support.
  • Node.js: The mongodb.github.io/node-mongodb-native/api-bson-generated/db_ref.html class provides support for DBRefs.
  • Perl: The https://metacpan.org/pod/MongoDB::DBRef class provides support for DBRefs.
  • PHP: It does not support DBRefs. You will have to traverse manually.
  • Python: The https://api.mongodb.com/python/current/api/bson/dbref.html class provides support for DBRefs.
  • Ruby: The https://api.mongodb.com/ruby/current/BSON/DBRef.html class provides support for DBRefs.
  • Scala: It does not support DBRefs. You will have to traverse manually.

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

3. 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.

Related Topic – MongoDB Indexing

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.