Web Programming TutorialsLearn about DBRefs and Manual References in MongoDB

Learn about DBRefs and Manual References in MongoDB

In the article “Learn How Data Modelling Works in MongoDB” of this MongoDB series, we discussed about the implementation of the normalized database structure in the MongoDB, where we used the manual references in order to build an embedded database structure. In the referenced relationship, we manually store the referenced document’s id into another document structure to build a relationship between the two documents in the MongoDB. There is another concept known as MongoDB DBRefs which is used when a document contains references to another document present in a different collections. We are going to discuss MongoDB DBRefs in detail in this article.

Comparison between DBRefs vs Manual References
The following data modelling is an example of Manual References, where we have created two separate document structures in the same collection or database ‘REFERENCE_MODEL’.

Document structure for a Blog

{
	heading: 'Life of an awesome girl',
	publish_date: '2016-11-27',
	description: 'An awesome girl...',
	permalink: 'http://awesomeblog.com/2016/12/life-of-an-awesome-girl',
	categories: ['Make', 'Travel', 'Fiction', 'girl'],likes: 56, 
      comments: [?]	
}

Document structure for a Comment

{
		name: 'Mohit',
		email:'[email protected]',
		phone:'123456789',
		message:'awesome blog',
		creationDate:'2016-11-27',
		like_flag:true
}

Since both the document structures are present in the same collection, we used the manual references concept in order to embed Comment documents into the Blog document as shown below.

> db.REFERENCE_MODEL.save ({
		name: 'Mohit',
		email:'[email protected]',
		phone:'123456789',
		message:'awesome blog',
		creationDate:'2016-11-27',
		like_flag:true
	});
> db.REFERENCE_MODEL.save ({
		name: 'Manu',
		email:'[email protected]',
		phone:'123456789',
		message:'I like this blog very much',
		creationDate:'2016-11-29',
		like_flag:true
	});
> db.REFERENCE_MODEL.save ({
		name: 'Appy',
		email:'[email protected]',
		phone:'123456789',
		message:'Simply Awesome',
		creationDate:'2016-11-28',
		like_flag:true
	});
> db.REFERENCE_MODEL.find();
{ "_id" : ObjectId("58af83ffe0f61d146f1f72a0"), "name" : "Mohit", "email" : "[email protected]", "phone" : "123456789", "message" : "awesome blog", "creationDate" : "2016-11-27", "like_flag" : true }
{ "_id" : ObjectId("58af840ce0f61d146f1f72a1"), "name" : "Manu", "email" : "[email protected]", "phone" : "123456789", "message" : "I like this blog very much", "creationDate" : "2016-11-29", "like_flag" : true }
{ "_id" : ObjectId("58af8420e0f61d146f1f72a2"), "name" : "Appy", "email" : "[email protected]", "phone" : "123456789", "message" : "Simply Awesome", "creationDate" : "2016-11-28", "like_flag" : true }
>
db.REFERENCE_MODEL.save ({
	heading: 'Life of an awesome girl',
	publish_date: '2016-11-27',
	description: 'An awesome girl...',
	permalink: 'http://awesomeblog.com/2016/12/life-of-an-awesome-girl',
	categories: ['Make', 'Travel', 'Fiction', 'girl'],likes: 56, 
    comments: [
      ObjectId("58af83ffe0f61d146f1f72a0"),
	  ObjectId("58af840ce0f61d146f1f72a1"),
      ObjectId("58af8420e0f61d146f1f72a2")
   ]	
});

Now consider a case, where we may need to refer to the testimonials of an author of the blog which are present as the documents in a different collection. In such a case, we need to implement the concept of MongoDB DBRefs.

Implementation of the MongoDB DBRefs
In MongoDB, there are three important fields which should be used in order to implement DBRefs relationship as follows.

$ref − this field of MongoDB DBRefs is used to specify the collection of the referenced document.
$id − this field of MongoDB DBRefs is used to specify the _id field of the referenced document.
$db – it is an optional field of MongoDB DBRefs that contains the name of the database in which the referenced document is present.

The following is a sample user document that demonstrates the implementation of MongoDB DBRefs.

{
	heading: 'Life of an awesome girl',
	publish_date: '2016-11-27',
	description: 'An awesome girl...',
	permalink: 'http://awesomeblog.com/2016/12/life-of-an-awesome-girl',
	categories: ['Make', 'Travel', 'Fiction', 'girl'],likes: 56, 
      comments: [?],
      testimonials : {
       "$ref": "testimonial",
       "$id": ObjectId("5813eed6e6893b80c9ae5bba"),
       "$db": "author_testimonial"}
}

Example MongoDB Script for DBRefs concept

> db.author_testimonial.save ({heading: 'Life of an awesome girl', testimonial:'She is doing very good with this know and so far I know her, she is going to be very successful!'})
WriteResult({ "nInserted" : 1 })
> db.author_testimonial.find()
{ "_id" : ObjectId("58dc43d6448a4239ed9de434"), "heading" : "Life of an awesome girl", "testimonial" : "She is doing very good with this know and so far I know her, she is going to be very successful!" }
> db.REFERENCE_MODEL.save ({
... heading: 'Life of an awesome girl',
... publish_date: '2016-11-27',
... description: 'An awesome girl...',
... permalink: 'http://awesomeblog.com/2016/12/life-of-an-awesome-girl',
... categories: ['Make', 'Travel', 'Fiction', 'girl'],likes: 56,
...     comments: [
...       ObjectId("58af83ffe0f61d146f1f72a0"),
...       ObjectId("58af840ce0f61d146f1f72a1"),
...       ObjectId("58af8420e0f61d146f1f72a2")
...    ],
...    testimonials: {
...        "$ref": "testimonal",
...        "$id": ObjectId("58dc43d6448a4239ed9de434"),
...        "$db": "author_testimonial"}
... });
> db.REFERENCE_MODEL.find()
{ "_id" : ObjectId("58dc447a448a4239ed9de435"), "heading" : "Life of an awesome girl", "publish_date" : "2016-11-27", "description" : "An awesome girl...", "permalink" : "http://awesomeblog.com/2016/12/life-of-an-awesome-girl", "categories" : [ "Make", "Travel", "Fiction", "girl" ], "likes" : 56, "comments" : [ ObjectId("58af83ffe0f61d146f1f72a0"), ObjectId("58af840ce0f61d146f1f72a1"), ObjectId("58af8420e0f61d146f1f72a2") ], "testimonials" : DBRef("testimonal", ObjectId("58dc43d6448a4239ed9de434"), "author_testimonial") }
>

Explanation of the above script
In the above script, we have demonstrated both approaches manual references as well as MongoDB DBRefs approach simultaneously.

Firstly, we have inserted a testimonial document in the collection ‘author_testimonial’.
Inside the comments part of the document present in the collection ‘REFERENCE_MODEL’, we have used manual references approach to refer three comments present as a part of Comment document within the same collection or the database through their ObjectId reference. Below is the syntax.

"comments" : [ ObjectId("58af83ffe0f61d146f1f72a0"), ObjectId("58af840ce0f61d146f1f72a1"), ObjectId("58af8420e0f61d146f1f72a2") ]

Inside the testimonials part of the document present in the collection ‘REFERENCE_MODEL’, we are using MongoDB DBRefs approach to refer the testimonials present in another collection ‘author_testimonial’ after defining three fields (i.e. $ref, $id and $db) as shown below.

...        testimonials: {
...        "$ref": "testimonial",
...        "$id": ObjectId("58dc43d6448a4239ed9de434"),
...        "$db": "author_testimonial"}

Here, a testimonial will be picked up from the collection ‘author_testimonial’ which has the reference as ‘testimonial’ and ObjectId of the document as ‘ObjectId (“58dc43d6448a4239ed9de434”)’ in this collection.

Conclusion: –
In this chapter, we have revised the concept of manual references used for the data modelling in the MongoDB and compared it against the concept of MongoDB DBRefs, where the former is used when the references are to be made to the documents present in the same collection and the latter approach is used when the references are to be made to the documents present in the different collections.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -