DEV Community

Cover image for $lookup in MongoDB
Ifeanyi Chima
Ifeanyi Chima

Posted on • Edited 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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay