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:
-
Embedding documents — nesting one document inside another. This is convenient if related data is often used together.
-
References — storing identifiers of documents from another collection in a document. To retrieve related data, additional queries or aggregation with the
$lookupoperation 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.