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:

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

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"),   "$db": "W3CSCHOOLCC"},   "contact": "987654321",   "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.users.findOne ({"Name": "Tom Benzamin"}) >var dbref = user.address>db[dbref. $ref].findone ({"_id" :(dbref. $id)})

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

{   "_id": ObjectId ("534009e4d852427820000002"),   "building": "A, Indiana Apt",   "Pincode": 123456,   ' city ': ' Los Angeles ', ' 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.