$lookup
operator
Today, we would be looking at the $lookup
operator in MongoDB.
The $lookup
operator; is part of the aggregation pipeline. It is used to join a document from one collection to a document of another collection in the same database.
Note: Both collections should be in the same database.
$lookup
operator has 4 options.
from: The collection which we will take documents from.
localField: The field of the collection which we are currently performing our $lookup
query on.
foreignField: The field of the collection which we wil take documents from.
as: The name given to the resultant array.
Exercise
We would use the $lookup
operator to get all the documents from the post collection to the user collection.
Step 1: create a database called "Facebook".
Step 2: create two collections called "users" and "posts".
Step 3: Populate the collections with data
users
// users collection
{
"author": String
}
posts
// posts collection
{
"likes": Number,
"shares": Number,
"comments": Number,
"postAuthor": String
}
db.users.aggregate([
{$lookup: {
from: "posts",
localField: "author",
foreignField: "postAuthor",
as: "postData"
}}])
Note: The value of the localField and the value of the foreignField must be the same.
E.g
// users collection
{
author: "Joe"
}
// posts collection
{
postAuthor: "Joe"
}
Thank you, Please follow me
Top comments (0)