How to Run $unionWith
with an Atlas Search $search
Query
On this page
Starting in v6.0, the MongoDB $unionWith
aggregation stage
supports $search
inside the $unionWith
pipeline
option. Using $unionWith
, you can combine
$search
results from multiple collections in the same
database in the result set.
This tutorial demonstrates how to run a $unionWith
query
with $search
against the companies
and inspections
collections in the sample_training
database. It takes you through
the following steps:
Set up an Atlas Search index with dynamic mappings for the
companies
andinspections
collections in thesample_training
database.Run
$unionWith
query with$search
to perform a union of companies withmobile
in their name from thecompanies
collection with companies with same or similar business name in theinspections
collection.
Before you begin, ensure that your Atlas cluster meets the requirements described in the Prerequisites.
Note
To run a $unionWith
query with $search
, your
cluster must run MongoDB v6.0 or higher.
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 Indexes
In this section, you will create an Atlas Search index named default
on
all the fields in the companies
collection in the
sample_training
database. You will create another Atlas Search index
named default
on all the fields in the inspections
collection in the sample_training
database. You must perform the
following steps for each collection.
Navigate to the Atlas Search page for your project.
If it isn't already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it isn't already displayed, select your desired project from the Projects menu in the navigation bar.
Click your cluster's name.
Click the Search tab.
Enter the Index Name, and set the Database and Collection.
In the Index Name field, enter
default
.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_training
database, and select the collection.To create an index for the
companies
collection, selectcompanies
.To create an index for the
inspections
collection, selectinspections
.
Specify an index definition.
The following index definition dynamically indexes the fields of supported types in the collection. You can use the Visual Editor or the JSON Editor in the Atlas user interface to create the index.
Run $unionWith
with $search
to Search the Collections
➤ Use the Select your language drop-down menu to set the language of the example in this section.
In this section, you will connect to your Atlas cluster and run
the sample query against the indexed collections in the
sample_training
database.