How to Run $lookup
with an Atlas Search $search
Query
On this page
Starting in v6.0, the MongoDB $lookup
aggregation stage
supports $search
inside the $lookup
pipeline
option. Using $lookup
, you can join
multiple collections in the same database at query-time and run a
$search
query to further narrow down your search.
Note
$lookup
queries are not very performant because Atlas Search
does a full document lookup on the database for each document in the
collection. To learn more, see
Reduce $lookup
Operations.
This tutorial demonstrates how to run a $lookup
query
with $search
against the accounts
and customers
collections in the sample_analytics
database. It takes you through
the following steps:
Set up an Atlas Search index with dynamic mapping for the
accounts
collection in thesample_analytics
database.Run
$lookup
query with$search
to find customers from thecustomers
collections whose accounts have purchased bothCurrencyService
andInvestmentStock
products in theaccounts
collection.
Before you begin, ensure that your Atlas cluster meets the requirements described in the Prerequisites.
Note
To run $lookup
query with $search
, your
cluster must run MongoDB v6.0 or later. If not, Atlas Search displays the
following error message:
$_internalSearchMongotRemote is not allowed within a $lookup's sub-pipeline.
To learn more, see Upgrade Major MongoDB Version for a Cluster.
Required Access
To create an Atlas Search index, you must have Project Data Access Admin
or higher access to the project.
Create the Atlas Search Index
Create an Atlas Search index named lookup-with-search-tutorial
on all the
fields in the sample_analytics.accounts
collection.
Navigate to the Atlas Search page for your project.
If it is not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it is not already displayed, select your desired project from the Projects menu in the navigation bar.
Click your cluster's name.
Click the Atlas Search tab.
Enter the Index Name, and set the Database and Collection.
In the Index Name field, enter
lookup-with-search-tutorial
.Note
If you name your index
default
, you don't need to specify anindex
parameter when using the $search pipeline stage. Otherwise, you must specify the index name using theindex
parameter.In the Database and Collection section, find the
sample_analytics
database, and select theaccounts
collection.
Specify an index definition.
The following index definition dynamically indexes the fields of supported types in the collection. You can use the Atlas Search Visual Editor or the Atlas Search JSON Editor in the Atlas user interface to create the index.
Run $lookup
with $search
to Search the Collections
➤ Use the Select your language drop-down menu on this page to set the language of the examples in this section.
Connect to your Atlas cluster and run the sample query against the
indexed collections in the sample_analytics
database.