Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

MongoDB Database References

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:


DBRefs vs Manual References

Consider a scenario where 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 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 form of a DBRef:



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

The meanings of the three fields are:

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



{

   "_id":ObjectId("53402597d852426020000002"),

   "address": {

   "$ref": "address_home",

   "$id": ObjectId("534009e4d852427820000002"),

   "$db": "runoob"},

   "contact": "987654321",

   "dob": "01-01-1991",

   "name": "Tom Benzamin"

}

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

In the following code, we find the user address information with the specified id in the 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 in the address_home collection:



{

   "_id" : ObjectId("534009e4d852427820000002"),

   "building" : "22 A, Indiana Apt",

   "pincode" : 123456,

   "city" : "Los Angeles",

   "state" : "California"

}