WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

MongoDB - Database References


Referenced Relationships also referred to as Manual References in which we manually store the referenced document's id inside other document. However, in cases where a document contains references from different collections, we can use MongoDB DBRefs.

DBRefs vs Manual References

As an example scenario, where we would use DBRefs instead of manual references, consider a database where we are storing different types of addresses (home, office, mailing, etc.) in different collections (address_home, address_office, address_mailing, etc).

Using DBRefs

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 and contains the name of the database in which the referenced document lies

Consider a sample user document having DBRef field address as shown in the code snippet
{
    "_id":ObjectId("\CfLbW+g4r}9M.6F"),
    "address": {
    "$ref": "address_home",
    "$id": ObjectId("\CfLbW+g4r}9M.6F"),
    "$db": "welookups"},
    "contact": "987654321",
    "dob": "11-12-2000",
    "name": "David"
}
The address DBRef field here specifies that the referenced address document lies in address_home collection under welookups database and has an id of \CfLbW+g4r}9M.6F. The following code dynamically looks in the collection specified by $ref parameter (address_home in our case) for a document with id as specified by $id parameter in DBRef.
>var user = db.users.findOne({"name":"David"})
>var dbRef = user.address
>db[dbRef.$ref].findOne({"_id":(dbRef.$id)})






Welookups is optimized for learning.Copy right 2018 kumar aditya singh .
All Right Reserved and you agree to have read and accepted our term and condition.
All Rights Reserved.