EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MongoDB Tutorial Lookup in MongoDB
Secondary Sidebar
MongoDB Tutorial
  • Commands
    • Mongodb updateMany
    • MongoDB Aggregation
    • Mongodb unwind
    • Mongodb where
    • MongoDB BSON
    • MongoDB Filter
    • Mongodb Match
    • MongoDB sort by date
    • MongoDB Limit()
    • MongoDB Atlas Login
    • MongoDB Relational Database
    • MongoDB count
    • MongoDB Aggregate
    • MongoDB Distinct
    • MongoDB Unique
    • MongoDB find
    • MongoDB findOne()
    • MongoDB insert
    • MongoDB Delete
    • MongoDB Update
    • Lookup in MongoDB
    • order by in MongoDB
    • MongoDB $regex
    • MongoDB $elemMatch
    • MongoDB ObjectId()
    • MongoDB Skip()
    • MongoDB findAndModify
    • Mongodb findOneAndUpdate
    • MongoDB Date Query
    • MongoDB Timestamp
    • MongoDB sort()
    • MongoDB group by
    • MongoDB Join
  • Basics
    • What is MongoDB
    • How To Install MongoDB
    • MongoDB Tools
    • MongoDB GUI Tools
    • MongoDB Versions
    • MongoDB Commands
    • Advantages of MongoDB
    • MongoDB Features
    • Is MongoDB NoSQL
    • Is MongoDB Open Source
    • Build Web Applications using MongoDB
    • MongoDB Data Types
    • MongoDB Administration
    • Data Modeling in MongoDB
    • MongoDB vs Elasticsearch
    • MariaDB vs MongoDB
    • Firebase vs MongoDB
  • Advanced
    • MongoDB Array
    • PostgreSQL ARRAY_AGG()
    • Indexes in MongoDB
    • MongoDB create Index
    • MongoDB Collection
    • MongoDB List Collections
    • MongoDB Capped Collections
    • MongoDB Delete Collection
    • Mongodb show collections
    • MongoDB Auto Increment
    • MongoDB Triggers
    • MongoDB Projection
    • Replication in MongoDB
    • MongoDB Database
    • Mongo DB Create Database
    • MongoDB Compass
    • MongoDB Users
    • MongoDB Authentication
    • MongoDB GridFS
    • MongoDB Relationships
    • MongoDB MapReduce
    • MongoDB Geospatial
    • MongoDB Monitoring
    • Backup in MongoDB
    • MongoDB Sharding
    • MongoDB Java Drivers
    • MongoDB Import
    • Mongo Database Interview Questions
    • MongoDB Join Two Collections
    • MongoDB Group by Multiple Fields
    • MongoDB Pagination
    • MongoDB Replica Set
    • MongoDB Bulk Update
    • MongoDB greater than
    • MongoDB Encryption
    • MongoDB find in array
    • MongoDB like query
    • Mongodb shell
    • MongoDB port
    • MongoDB Query Operators
    • MongoDB Web Interface
    • MongoDB Query Array
    • MongoDB Transactions
    • MongoDB Not In
    • MongoDB not null
    • MongoDB npm
    • MongoDB Remove

Lookup in MongoDB

By Priya PedamkarPriya Pedamkar

Lookup in MongoDB

Introduction to Lookup in MongoDB

MongoDB consists of aggregation pipeline, A  framework based on the concept of pipelining documents. Documents enter a pipeline with multiple stages consisting of multiple operators such as match and group to aggregate data accordingly. Lookup is one of the aggregation pipeline stages which enables joining data to an input collection (The collection on which the query is currently being executed) from a lookup collection (The collection from which data is retrieved to join) and returns a document consisting of an array of matched data from lookup collection. In this topic, we are going to learn about Lookup in MongoDB.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Equality Match $lookup

Lookup in MongoDB syntax 1

  • from: this is the collection from which documents are joined
  • localField: This is the field in the input collection
  • foreignField: This is the field from the lookup collection which is matched against the localField
  • as: This is the field where all the matched results from lookup collection are stored in the form of an array. 

Join and Uncorrelated subqueries

Lookup in MongoDB syntax 2

  • Pipeline: Pipelining is staging all the matches and filters in order of execution
  • let: let is used to define variables in specific expressions and access the expression’s return results.

Characteristics of $lookup

  1. $lookup supports uncorrelated subqueries and equality matches.
  2. Applications that use MongoDB for data act as clients for the MongoDB server.$lookup processes data on the server-side, making it much faster than performing multiple DB requests and processing the results on the client-side.
  3. $lookup scans the entire lookup collection to see if there is a match for the filters mentioned for every document in the input collection. Therefore efficient searching techniques like indexing are required for huge data sets.
  4. In the pipeline, the order is essential as the data gets aggregated w.r.t the operator/rule mentioned first in the pipeline.

Constraints on the usage of $lookup

  1. Both the collections should be in the same database.
  2. lookup collection should be shared

Examples of Lookup in MongoDB

Here are the examples of Lookup in MongoDB mention below

1. Single Equality join using $lookup

Create a collection of students with the following documents:

Code:

db.students .insertMany([
{“id” : 1 , “pupil” : “John” , “std” : 6, “ht” : 153 , “wt” : 43},
{“id” : 2 , “pupil” : “Jack” , “std” : 6, “ht” : 164 , “wt” : 54},
{“id” : 3 , “pupil” : “Jill” , “std” : 6, “ht” : 173 , “wt” : 69},
{“id” : 4 , “pupil” : “william” , “std” : 6}
])

Output:

Examples of Lookup in MongoDB 1.1

Another collection of sports contains the following documents :

Code:

db.sports .insertMany([
{“id” : 1, “sport” : “Basketball” , “winner” : “John”},
{“id” : 2, “sport” : “TT”             , “winner” : “Jack”},
{“id” : 3, “sport” : “Tennis”       , “winner” : “John”},
{“id” : 4, “sport” : “carrom”      , “winner” : “william”},
{“id” : 5, “sport” : “fencing”      , “winner” : “william”},
{“id” : 6}])

Output:

Examples of Lookup in MongoDB 1.2

The following query joins matches from sports collection to students collection based on the field value pupil and winner in students and sports respectively

Code:

db.students.aggregate([
{
$lookup:
{
from : “sports”,
localField : “pupil”,
foreignField : “winner”,
as : “games”
} } ] )

When the above query is executed, the following result is displayed.

Output:

Examples of Lookup in MongoDB 1.3

2.  $lookup with an Array

Create a collection genres with the following documents

Code:

db.geners.insertMany( [
{ _id: 1, title: "Notebook", genrelist: [ "comedy", "romance", "fiction" ]},
{ _id: 2, title: "Anabelle", genrelist: [ "horror", "fiction" ]}
])

Output:

Examples of Lookup in MongoDB 2.1

Create another collection of movies with the following documents

Code:

db.movies.insertMany( [
{ _id: 1, name: "HarryPotter", "type": "fiction", rating: "A" },
{ _id: 2, name: "LOTR", "type": "fiction", rating: "D" },
{ _id: 3, name: "Witchcraft", "type": "horror", rating: "A" },
{ _id: 4, name: "panda", "type": "romance", rating: "A" },
{ _id: 5, name: "What is new", "type": "comedy", rating: "A" },
{ _id: 6, name: "Date", "type": "romance", rating: "D" }
])

Output:

Examples of Lookup in MongoDB 2.2

When querying a localField which is of type array, $lookup matches every element’s value to the foreign field’s value in lookup collection. It returns an array similar to an equality match.

Code:

db.geners.aggregate([
{
$lookup:
{
from : “movies”,
localField : “genrelist”,
foreignField : “type”,
as : “movie”
} } ] ).pretty()

When the above query is executed, the following result is displayed.

Output:

Examples of Lookup in MongoDB 2.3

3. $lookup with $mergeobjects

$lookup returns documents with from the input collections joined with the matched documents from the lookup collection, but the documents in the original input collection are added in the form of an array which consists of all the matches. $mergeobjects enables the users to modify the documents in input collection based on the filters set in $lookup.

Create a collection of groceries and insert the following documents:

Code:

db.groceries .insertMany([
{“id” : 1 , “item” : “cashew” , “qnt” : 6, “price” : 43},
{“id” : 2 , “item” : “cookie” ,   “qnt” : 4, “price  ” : 54}
])

Output:

Examples of Lookup in MongoDB 3.1

Create another collection stock and insert the following documents.

Code:

db.stock .insertMany([
{“id” : 1 , “item” : “cashew” , “description” : “salted cashews”, “isle” : 43},
{“id” : 2 , “item” : “cookie” ,   “description” : “oat and raisin cookies”, “isle ” : 54}
])

Output:

Examples of Lookup in MongoDB 3.2

Code:

db.groceries.aggregate([
{
$lookup: {
from: "stock",
localField: "item",
foreignField: "item",
as: "fromItems"
}
},
{
$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$fromItems", 0 ] }, "$$ROOT" ] } }
},
{ $project: { fromItems: 0 } }
])

This will read all the matching documents from the stock collection, and When the above query is executed, the following result is displayed.

Output:

Examples 3.3

4. Uncorrelated Subquery

Uncorrelated subqueries are independent of the outer query. They don’t have references to the object in the outer/parent statement.

Create a collection sports

Code:

db.sports.insert([
{ "_id" : 1, "student" : "Ann Aardvark", “sports”: [ "basketball","Throwball" ] },
{ "_id" : 2, "student" : "Zoe Zebra", “sports”: [ "Tennis","TT"] },
])

Output:

Example 4.1

Code:

db.winners.insert([
{ "_id" : 1, “sport”: "basketball", “place”: 1, date: new Date("2018-01-01") },
{ "_id" : 2, “sport”: "basketball", “place”: 4, date: new Date("2018-03-14") },
{ "_id" : 3, “sport”: "basketball", “place”:2, date: new Date("2018-07-15") },
{ "_id" : 4, “sport”: "TT", “place”: 6, date: new Date("2017-01-01") },
{ "_id" : 5, “sport”: "TT", “place”: 8, date: new Date("2017-07-16") }
])

Output:

Example 4.2

This query matches the sport basketball and in all the document in lookup collection and picks the place and date, creates a new field win of type array and stores all the matches in the array.

Code:

db.sports.aggregate([
{
$lookup:
{
from: "winners",
pipeline: [
{ $match: { sport: "basketball" } },
{ $project: { _id: 0, date: { place: "$place", date: "$date" } } },
{ $replaceRoot: { newRoot: "$date" } }
],
as: "win"
}
}
]).pretty()

When the above query is executed, the following result is displayed.

Output:

Example 4.3

Recommended Articles

This is a guide to Lookup in MongoDB. Here we discuss the characteristics and examples of Lookup in MongoDB along with the query and output. You can also go through our other suggested articles to learn more –

  1. Advantages of MongoDB
  2. MongoDB Tools
  3. What is MongoDB?
  4. MongoDB Commands
  5. Guide to Top 11 MongoDB List Collections
  6. MongoDB Limit() | How to Works?
Popular Course in this category
MongoDB Training Program (4 Courses, 2 Projects)
  4 Online Courses |  2 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Oracle Training (17 Courses, 8+ Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
SQL Training Program (10 Courses, 8+ Projects)4.7
Oracle DBA Database Management System Training (2 Courses)4.7
MS SQL Training (16 Courses, 11+ Projects)4.7
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more