Querying with the Compound Operator
Overview
In this guide, you will learn how to use multiple search operators in a compound query by using the aggregation pipeline.
Time required: 5 minutes
What You'll Need
A MongoDB account. See Sign Up for a MongoDB Account.
An Atlas cluster. See Create a Cluster.
Sample datasets loaded into your cluster.
A search index with default settings and dynamic indexing. To create a default dynamic index, see Build a Dynamic Index.
Procedure
In Atlas, go to the Clusters page for your project.
If it's not already displayed, select the organization that contains your desired project from the Organizations menu in the navigation bar.
If it's not already displayed, select your desired project from the Projects menu in the navigation bar.
If it's not already displayed, click Clusters in the sidebar.
The Clusters page displays.
Click the Collections tab.
Click the sample_supplies
database,
then click the sales
collection.
Run a compound query on your index in the Aggregations tab.
Click the Aggregation tab.
Click + Add Stage to begin creating your aggregation pipeline.
In the stage window, click on the dropdown menu labeled Select and select the $search stage.
Replace the placeholder code with the following query.
{ "compound": { "filter": [{ "text": { "query": "Online", "path": "purchaseMethod" } }], "should": [{ "text": { "query": "notepad", "path": "items" } }] } }
This query uses the compound
operator with:
The
filter
clause to return only documents with apurchaseMethod
ofOnline
.The
should
clause to return documents with anitems
field that containsnotepad
to have a higher score than those without.
Review the results of the compound query.
In the right-hand pane, your results should include a list of documents that resemble the following sample document:
items: Array 0: Object 1: Object 2: Object name: "notepad" ... storeLocation: "Denver" customer: Object couponUsed: false purchaseMethod: "Online" _id: ObjectID('5bd761dcae323e45a93cd06e') saleDate: 2013-11-22T18:49:45.212+00:00
Note
The fields don't always appear in the same order for every returned document.
You can expand Array
and Object
fields to view their
contents by clicking on them.
Summary
If you successfully completed the procedure in this guide, you have created an Atlas Search aggregation stage with a compound operator, and have seen how different clauses in the operator interact to focus your search results across multiple axes. In the next guide, you will learn how to group search results using facets.
Retrieve documents in MongoDB with counts of specific values.