Easy Tutorial
❮ Mongodb Dropdatabase Mongodb Limit Skip ❯

MongoDB Database References

In the previous chapter on MongoDB relationships, we mentioned MongoDB references to standardize document structures.

MongoDB references come in two types:


DBRefs vs Manual References

Consider a scenario where we store different types of addresses (home, office, mailing, etc.) in different collections (address_home, address_office, address_mailing, etc.).

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


Using DBRefs

The format of DBRef is:

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

The three fields represent:

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

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

The address DBRef field specifies that the referenced address document is in the address_home collection of the tutorialpro database, with the ID 534009e4d852427820000002.

The following code finds the user address information in the specified collection by specifying the $ref parameter (address_home 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 from the address_home collection:

{
   "_id" : ObjectId("534009e4d852427820000002"),
   "building" : "22 A, Indiana Apt",
   "pincode" : 123456,
   "city" : "Los Angeles",
   "state" : "California"
}
❮ Mongodb Dropdatabase Mongodb Limit Skip ❯