MongoDB Database References

In the previous chapter on MongoDB relationships, we mentioned MongoDB references to standardize data structure documents.

There are two types of MongoDB references:

  • Manual References
  • DBRefs

DBRefs vs Manual References

Consider such a scenario: we store different addresses (home address, office address, mailing address, etc.) in different collections (address_home, address_office, address_mailing, etc.).

In this way, when we access different addresses, we also need to specify the collection. When a document references documents from multiple collections, we should use DBRefs.


Using DBRefs

DBRef format:

{ $ref : , $id : , $db :  }

The meaning of the three fields is:

  • $ref: collection name
  • $id: the referenced id
  • $db: database name, optional parameter

In the following example, the user data document uses DBRef for the field address:

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

addressThe DBRef field specifies that the referenced address document is in the address_home collection under the example database, with id 534009e4d852427820000002.

In the following code, we specify the $ref parameter (address_home collection) to find the user address information with the specified id in the collection:

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

The above example returns the address data in the address_home collection:

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