MongoDB Database Reference

Source: Internet
Author: User
Tags findone

There are two types of MongoDB references:

    • Manual reference (Manual References)
    • DBRefs
DBRefs vs Manual Reference

Consider a scenario in which 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 the collection, a document that references the document from multiple collections, and we should use DBRefs.

Using DBRefs

form of Dbref:

{:,:,:}

The three fields represent the meaning:

    • $ref: Collection Name
    • $ID: The ID of the reference
    • $DB: Database name, optional parameters

The user data document in the following example uses the Dbref, field address:

{   "_ID":ObjectId("53402597d852426020000002"), "Address": { "$ref": "Address_home",  "$id" :  Objectid "534009e4d852427820000002"  span class= "str" > "$db" :  "W3CSCHOOLCC" },< Span class= "PLN" >  "contact" :  "987654321" Span class= "pun" >,  "DOB" :  "01-01-1991" ,  "name" :  "Tom benzamin" }         

Address The Dbref field specifies that the referenced address document is a W3CSCHOOLCC database under the Address_home collection, with an ID of 534009e4d852427820000002.

In the following code, we look up the user address information for the specified ID in the collection by specifying the $REF parameter (Address_home collection):

>Var user = Db.. Findone ({ "name" : "Tom Benzamin" >var Dbref = User.>db[dbref $ref findone ({:( Dbref. $id               

The above instance returns the address data from the Address_home collection:

{   "_ID" : objectid ( "534009e4d852427820000002" Span class= "pun"),   "building"  :  "A, Indiana Apt" ,  "Pincode"  : 123456, "city"  :  "Los Angeles" Span class= "pun" >,  "state"  :   "California" }       

MongoDB Database Reference

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.