EventGet 50% off your ticket to MongoDB.local London on October 2. Use code WEB50Learn more >>
MongoDB Developer
MongoDB
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Productschevron-right
MongoDBchevron-right

Optimizing $lookup Performance Using the Power of Indexing

Shani Roffe7 min read • Published Aug 30, 2024 • Updated Aug 30, 2024
MongoDB
Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Have you ever had to join data from two collections and wanted to know how to improve the queries performance? Let's walk through how indexing can help power faster search results when using $lookup.

What is $lookup?

$lookup is a stage in an aggregation pipeline that performs a left outer join to a collection to filter in documents from the "joined" collection for processing. $lookup creates a new array in the pipeline, where each field is a returned document from the $lookup.
Indexes within a database are extremely powerful, as they can significantly reduce resource usage and query duration. Without them, the queries would have to scan every document in a collection in order to return the query result, which takes a lot of time and resources. It is therefore very important to have indexes in place when using $lookup to “join” collections.
For $lookup performance to be optimized, it is good practice to have indexes on both collections, the source collection and joining collection. That way, the main query on the source collection will benefit from an index as will the query on the joined collection.

Journey of performance improving through the use of indexes

To walk you through how we can optimize $lookup queries, we will use movie data as an example. Our query uses data from two collections, genres and movies. We want to find all the movies that fall under the genres of comedy and drama.
enter image description here
Documents from source and joining collections
Collection: genres
Collection: movies
Desired Output:
We can achieve our task of finding all the comedy and drama movies by creating an aggregation pipeline on the genres collection and joining data from the movies collection. It is possible to create the aggregation on the movies collection, but for illustration purposes, we are going to assume we are joining from genres to movies.
  1. We want to ensure that we are only going to return the documents that are under the genre of comedy and drama by using the $match stage.
  2. In the $lookup stage, we will perform a left join on the movies collection to retrieve the movie titles and years:
  • The from field is our joining collection. In this case, it's the movies collection.
  • In the let, we are assigning the “_id” field in the genres collection to the variable “genre_id”, which we will use in the pipeline.
  • In the pipeline, we will use $match to take the documents from the movies collection where the genre_id (from the genres collection) corresponds to the array “genre_codes” (from the movies collection). Then, we will use $project to only return the title and year of each movie.
Let's run the aggregation and see how it is performing:
Results:
Now, we know that using indexes improves the performance of the program, so let's create them on their respective collections:
enter image description here
Let's run the aggregation and see how the performance improved by adding indexes:
Results:
Uh oh! We can see through the executionStats output that this aggregation did not use the index on the movies that we created. The totalDocsExamined is 42, meanwhile there are only eight documents in the genres collection and 21 in the movies collection! The reason the number of documents examined can get so high is because for each of the two genres, it scans the entire movies collection. This leads to two collection scans, which is suboptimal and can lead to significant performance issues. When a $lookup takes place, each document of the source collection will scan the entire joining collection, causing the amount of documents scanned to be significantly high compared to the amount of documents returned.
The reason that this method failed to use an index is that $expr cannot use an index when one of the operands is an array, like the $genre_codes field in this example.

Using an index on the joining collection

To avoid using an array operand with $expr to evaluate if the genre codes are present, we can use localField and foreignField instead, which will provide the same functionality:
  • localField is the field within genres, the source collection that we want to perform an equality match with foreignField, in this case _id.
  • foreignField is the field within movies, the joining collection where we want to perform an equality match with localField, in this case genre_codes.
  • Since we already established which variables we are going to be using in pipeline through the localField and foreignField, we can leave the let empty, and remove the $match stage from our pipeline.
Aggregate:
By utilizing localField and foreignField, we are able to perform an equality match with fields from different collections without using $expr and $in.
We can see from the .explain() output that there was a 65% improvement in performance. We have successfully used the index genre_codes_1 on the movies collection. This improves performance as we see only 19 documents were examined. However, we can improve performance even more by including the projection fields in the index.

Performing a covered query on the joining collection

Now that we see that implementing localField and foreignField will use the indexes we created, let's optimize the query by including the projection fields as part of the index to perform a covered query.
Yay! Our index was used and it performs a covered query (a query that only uses the index to retrieve results)! :) The explain output shows that totalDocsExamined is 0, which means it did not have to fetch any documents, whether for evaluating or projecting. It was all in the index already, ready for use.
Hopefully, this has been a thorough illustration of how you can optimize the performance of $lookup when one of the operands is an array. If you would like to test this in your local environment, please find instructions on creating the movies and genres collections below.
Thanks for reading!

For more information on indexes and $lookup

Top Comments in Forums
There are no comments on this article yet.
Start the Conversation

Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Quickstart

How to Use MongoDB Transactions in Node.js


Aug 24, 2023 | 10 min read
Code Example

Example Application for Dog Care Providers (DCP)


Jul 12, 2024 | 3 min read
Tutorial

The Great Continuous Migration: CDC Jobs With Confluent Cloud and Relational Migrator


Aug 23, 2024 | 11 min read
Tutorial

Written in the Stars: Predict Your Future With Tensorflow and MongoDB Charts


Aug 21, 2024 | 15 min read
Table of Contents