Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

MongoDB database reference


May 17, 2021 MongoDB


Table of contents


MongoDB database reference

In the previous section, we mentioned the MongoDB reference to regulate the data structure document.

There are two types of MongoDB references:

  • Manual References
  • DBRefs

DBRefs vs manual reference

Consider a scenario where we store different addresses (address, office address, email address, etc.) in different collections (address_home, address_office, address_mailing, etc.).

This way, when we call different addresses, we also need to specify a collection, a document references documents from multiple collections, and we should use DBRefs.


Use DBRefs

In the form of DBRef:

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

The three fields represent the meaning of:

  • $ref: Collection name
  • $id: The referenced id
  • $db: database name, optional parameters

The following example of a user data document uses DBRef, the field address:

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

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

In the following code, we look for the user $ref information for the specified id in the collection by specifying the address_home parameter (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 address_home data from the collection:

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