The ‘$lookup‘ operator in the MongoDB aggregation framework is used to perform a left outer join between two collections in a MongoDB database. The operator retrieves matching documents from a "foreign" collection and adds them to the resulting documents from the primary collection.
The ‘$lookup‘ operator takes an object as its argument that specifies the foreign collection, specific local and foreign fields that need to match, the name of the array to which the result should be added, and any additional options.
Here’s an example:
Suppose we have two collections in a database - orders and products. The orders collection contains an array of ‘productIds‘ while the products collection has information about the products. We want to retrieve all the orders along with their corresponding products. We can achieve this using the ‘$lookup‘ operator as follows:
db.orders.aggregate([
{
$lookup: {
from: "products",
localField: "productIds",
foreignField: "_id",
as: "products"
}
}
])
In this example, the ‘$lookup‘ operation joins the orders collection with the products collection, matching the ‘productIds‘ arrayin each document in the ‘orders‘ collection with ‘_id‘ field in the ‘products‘ collection.
The resulting output will contain the matched documents from products collection as an array field named ’products’.
{
"_id": ObjectId("6130c424a416f244e16a0dcb"),
"customer": "John Doe",
"productIds": [
ObjectId("6130d67e7479190c69b9f9a7"),
ObjectId("6130d6357479190c69b9f99c"),
ObjectId("6130d6867479190c69b9f9a8")
],
"status": "delivered",
"products": [
{
"_id": ObjectId("6130d6357479190c69b9f99c"),
"name": "Product A",
"price": 10.5
},
{
"_id": ObjectId("6130d67e7479190c69b9f9a7"),
"name": "Product B",
"price": 5.5
},
{
"_id": ObjectId("6130d6867479190c69b9f9a8"),
"name": "Product C",
"price": 18.0
}
]
}
In this result, we can see for every order document, the ‘$lookup‘ operator searched for matching product documents and added them to the ‘products‘ field. If there was no match, the ‘products‘ field would simply be an empty array.
In summary, the ‘$lookup‘ operator is a powerful aggregation pipeline tool that allows MongoDB to simulate a ‘left outer join‘ operation between two collections in the database. This operator can handle complex queries with ease and is essential when working with related documents in MongoDB databases.