Sobes.tech
Junior — Middle

Is it possible to establish relationships between different collections in a MongoDB database?

sobes.tech AI

Answer from AI

MongoDB does not have traditional relations like relational databases, but you can establish relationships between collections in two main ways:

  1. Embedding documents — nesting one document inside another. This is convenient if related data is often used together.

  2. References — storing identifiers of documents from another collection in a document. To retrieve related data, additional queries or aggregation with the $lookup operation are needed.

Example of using $lookup to relate the "orders" and "customers" collections:

db.orders.aggregate([
  {
    $lookup: {
      from: "customers",
      localField: "customerId",
      foreignField: "_id",
      as: "customerInfo"
    }
  }
])

Thus, MongoDB supports relationships between collections, but implements them differently than relational DBMS.

Is it possible to establish relationships between… - sobes.tech