mongodbHow to implement one-to-many relation in MongoDB?
MongoDB supports one-to-many relationships using the $lookup
operator. This operator allows you to join two collections together and return the matching documents from both collections.
For example, the following code will join the orders
collection with the products
collection and return the matching documents:
db.orders.aggregate([
{
$lookup:
{
from: "products",
localField: "productId",
foreignField: "_id",
as: "products"
}
}
])
The code above will return the following output:
{
"_id" : ObjectId("5f3d7f9f8f9f9f9f9f9f9f9f"),
"productId" : ObjectId("5f3d7f9f8f9f9f9f9f9f9f9f"),
"products" : [
{
"_id" : ObjectId("5f3d7f9f8f9f9f9f9f9f9f9f"),
"name" : "Product 1",
"price" : 10
}
]
}
Code explanation
$lookup
- This is the operator used to join two collections.from
- This is the collection to join with.localField
- This is the field in the current collection to match with the foreignField.foreignField
- This is the field in the foreign collection to match with the localField.as
- This is the name of the array field that will contain the matching documents from the foreign collection.
Helpful links
More of Mongodb
- How to use watch in MongoDB?
- How to use triggers in MongoDB?
- How to list MongoDB users?
- How to use MongoDB queue?
- How to implement pagination in MongoDB?
- How to create a many to many relation in MongoDB?
- What is MongoDB default port?
- How to select specific fields in MongoDB query?
- How to query with "not equal" condition in MongoDB?
- How to use MongoDB query with "or" condition?
See more codes...