MongoDB is a popular NoSQL database that stores data in a document-based format. Unlike traditional SQL databases, MongoDB does not support the use of JOINS to combine data from multiple collections. However, there are still ways to achieve similar functionality in MongoDB by using the $lookup and $unwind operators.
The $lookup
operator is used to perform a left outer join on two collections. It allows you to combine data from two collections and return the results in a single document. The basic syntax for the $lookup operator is as follows:
{
$lookup: {
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the joined collection>,
as: <output array field>
}
}
For example, let’s say we have two collections: “orders” and “customers”. The “orders” collection has a field “customer_id” that references the “_id” field of the “customers” collection. To join these two collections and get the customer’s name for each order, we can use the following query:
<code>db.orders.aggregate([ { $lookup: { from: "customers", localField: "customer_id", foreignField: "_id", as: "customer" } } ])</code>
This will return a result set where each document in the “orders” collection will have a new field called “customer” that contains the matching documents from the “customers” collection. The output will be something like this:
{ "_id": ObjectId("5f6d7f23bc45e913f2c5a8b5"), "product": "Apple", "quantity": 2, "customer_id": ObjectId("5f6d7f23bc45e913f2c5a8b4"), "customer": [ { "_id": ObjectId("5f6d7f23bc45e913f2c5a8b4"), "name": "John Smith", "email": "john.smith@example.com" } ] }
It’s also possible to perform left outer join and right outer join in MongoDB. A left outer join can be done by using the $lookup stage followed by a $unwind stage, like this:
The
$unwind
operator is used to “flatten” an array field in a document, effectively turning a single document into multiple documents.
db.orders.aggregate([ { $lookup: { from: "customers", localField: "customer_id", foreignField: "_id", as: "customer" } }, { $unwind: "$customer" } ])
This will return all documents from the “orders” collection and the matching documents from the “customers” collection. If there’s no match, the “customer” field will be null.
A right outer join can be done by reversing the order of the collections in the $lookup stage and using a $unwind stage.
In MongoDB, $lookup is a powerful feature that allows you to join data from different collections, similar to SQL JOINs. It’s a convenient way to combine data and improve the performance of your queries.