English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MongoDB Database References

As seen in the last chapter on MongoDB relationships, to implement a normalized database structure in MongoDB, we use the concept of referenced relationships (also known as manual references), where we manually store the id of the referenced document in other documents. However, when documents contain references from different collections, we can use MongoDB DBRefs.

DBRef vs Manual Reference

As an example scenario, consider a database where we store different types of addresses (home, office, mailing, etc.) in different collections (address_home, address_office, address_mailing, etc.). Now, when a document in the user collection references an address, it also needs to specify the collection to be searched based on the address type. In cases where a document references documents in multiple collections, we should use DBRefs.

Using DBRef

There are three fields in DBRefs-

  • $ref −This field specifies the collection of the referenced document

  • $id −This field specifies the _id field of the referenced document

  • $db −This is an optional field that contains the name of the database where the referenced document is located

Consider a sample user document with a DBRef fieldaddressAs shown in the code snippet-

{
   "_id": ObjectId("53402597d852426020000002")
   "address": {
   "$ref": "address_home",
   "$id": "ObjectId("534009e4d852427820000002")
   "$db": "w"3codebox",
   "contact": ""987654321",
   "dob": "0"1-01-1991",
   "name": "Tom Benzamin"
}

Here, the address DBRef field specifies that the referenced address document is located at w3The address_home collection under the codebox database contains an entry with id534009e4d8524278200000002.

The following code dynamically finds the document with the id specified by the $id parameter in the collection specified by the $ref parameter (in our case, address_home).

>var user = db.users.findOne({"name":"Tom Benzamin"})
>var dbRef = user.address
>db[dbRef.$ref].findOne({"_id":(dbRef.$id)})

The above code returnsaddress_homeThe following address document exists in the collection-

{
   "_id": ObjectId("534009e4d852427820000002")
   "building": ""22 A, Indiana Apt",
   "pincode": : 123456,
   "city": "Los Angeles",
   "state": "California"
}