3.32. MongoDB database reference

发布时间 :2025-10-25 12:32:57 UTC      

In the previous section of the MongoDB relationship, we mentioned the reference to MongoDB to standardize the data structure document.

There are two types of MongoDB references:

  • Manual reference (Manual References)

  • DBRefs

3.32.1. 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.).

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

3.32.2. Use DBRefs

The form of DBRef:

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

The meanings of the three fields are:

  • $ref: collection name

  • $id: referenced id

  • $db: database name, optional parameter

DBRef and field address are used in the user data document in the following example:

{
   "_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 the address_home collection under the runoob database, and id is 534009e4d852427820000002.

In the following code, we find the user address information for the specified id in the collection by specifying the $ref parameter (the 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"
}
Principles, Technologies, and Methods of Geographic Information Systems  102

In recent years, Geographic Information Systems (GIS) have undergone rapid development in both theoretical and practical dimensions. GIS has been widely applied for modeling and decision-making support across various fields such as urban management, regional planning, and environmental remediation, establishing geographic information as a vital component of the information era. The introduction of the “Digital Earth” concept has further accelerated the advancement of GIS, which serves as its technical foundation. Concurrently, scholars have been dedicated to theoretical research in areas like spatial cognition, spatial data uncertainty, and the formalization of spatial relationships. This reflects the dual nature of GIS as both an applied technology and an academic discipline, with the two aspects forming a mutually reinforcing cycle of progress.