DEV Community

Cover image for $lookup in MongoDB
Ifeanyi Chima
Ifeanyi Chima

Posted on • Updated on

$lookup in MongoDB

$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
}
Enter fullscreen mode Exit fullscreen mode

posts

// posts collection
{
"likes": Number,
"shares": Number, 
"comments": Number,
"postAuthor": String
}
Enter fullscreen mode Exit fullscreen mode

db.users.aggregate([
{$lookup: {
  from: "posts",
  localField: "author",
  foreignField: "postAuthor",
  as: "postData"

}}])

Enter fullscreen mode Exit fullscreen mode

Note: The value of the localField and the value of the foreignField must be the same.

E.g

// users collection

{
 author: "Joe"
}
Enter fullscreen mode Exit fullscreen mode
// posts collection

{
 postAuthor: "Joe"
}
Enter fullscreen mode Exit fullscreen mode

Buy Me A Coffee

Thank you, Please follow me

HTML GitHub

Top comments (0)