Skip to content

MongoDB Database References

In MongoDB, we can use database references to represent relationships between documents. Database references allow us to reference one document from another, enabling associated queries on the data.

Basic Concepts

Types of Database References

  1. DBRef: The officially recommended database reference type in MongoDB.
  2. Manual Reference: Our own defined database reference type.

Structure of DBRef

DBRef is a document that contains the following fields:

  1. $ref: The name of the collection to reference.
  2. $id: The _id field of the document to reference.
  3. $db (optional): The name of the database to reference.

Creating a DBRef

javascript
// Create a DBRef
const dbRef = {
  $ref: "orders",
  $id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f90"),
  $db: "mydatabase"
}

// Embed the DBRef into the user document
db.users.updateOne(
  { _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f") },
  { $set: { orderRef: dbRef } }
)

Querying the Document Referenced by DBRef

javascript
// Query the user document
const user = db.users.findOne({ _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f") })

// Resolve the DBRef
const order = db[user.orderRef.$ref].findOne({ _id: user.orderRef.$id })

console.log(order)

Using $lookup to Resolve DBRef

In MongoDB, we can use the $lookup operator to resolve DBRef.

javascript
// Resolve the DBRef
db.users.aggregate([
  {
    $lookup: {
      from: "orders",
      localField: "orderRef.$id",
      foreignField: "_id",
      as: "order"
    }
  }
])

Manual References

In addition to DBRef, we can also use manual references to represent relationships between documents. A manual reference is when we directly store the _id field of another document in a document.

javascript
// User document
{
  _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f"),
  name: "John",
  email: "john@example.com",
  orderId: ObjectId("5e8f8f8f8f8f8f8f8f8f8f90")
}

// Order document
{
  _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f90"),
  product: "iPhone X",
  price: 999,
  quantity: 1
}

Querying the Document Referenced by Manual Reference

javascript
// Query the user document
const user = db.users.findOne({ _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f") })

// Query the order document
const order = db.orders.findOne({ _id: user.orderId })

console.log(order)

Using $lookup to Resolve Manual Reference

javascript
// Resolve the manual reference
db.users.aggregate([
  {
    $lookup: {
      from: "orders",
      localField: "orderId",
      foreignField: "_id",
      as: "order"
    }
  }
])

Comparison of DBRef and Manual References

Advantages of DBRef

  1. Standardization: DBRef is the officially recommended database reference type in MongoDB.
  2. Explicitness: DBRef explicitly points out the collection and database to reference.
  3. Readability: DBRef has a clearer structure and is easier to understand.

Disadvantages of DBRef

  1. Performance: Resolving DBRef requires additional query operations, which reduces query performance.
  2. Complexity: DBRef has a more complex structure and requires more code to resolve.

Advantages of Manual References

  1. Performance: Manual references have a simpler resolution process and higher query performance.
  2. Simplicity: Manual references have a simpler structure and require less code to resolve.

Disadvantages of Manual References

  1. Non-standardization: Manual references have no uniform format, which may lead to code inconsistencies.
  2. Implicitness: Manual references do not explicitly point out the collection and database to reference, which may cause confusion.

Summary

In MongoDB, we can use database references to represent relationships between documents. Database references allow us to reference one document from another, enabling associated queries on the data. MongoDB provides two types of database references: DBRef and manual references. DBRef is the official recommended database reference type, and it has a clearer structure and is easier to understand, but query performance is lower. Manual references have a simpler structure and higher query performance, but they have no uniform format, which may lead to code inconsistencies. When choosing a database reference type, we should decide according to actual needs.

Content is for learning and research only.