Read Data using Operators and Compound Queries¶
Author: MongoDB Documentation Team
In the previous read guide, Read Data from MongoDB With Queries,
you read data using embedded fields and dot notation
. In
this guide, you will:
- read data from the
inventory
collection with MongoDB’s comparison operators. - combine query criteria to make compound queries
Time required: 30 minutes
What You’ll Need¶
- If you have not already installed a client (e.g. a driver, MongoDB Compass, or the
mongo
shell), complete the Connect to MongoDB guide before attempting this guide.
- If you have not already installed a client (e.g. a driver, MongoDB Compass, or the
mongo
shell), complete the Connect to MongoDB guide before attempting this guide. - Enable Auth on your local instance of MongoDB.
Warning
If you are running MongoDB locally and have not enabled authentication, your MongoDB instance is not secure.
Check Your Environment¶
You will need to ensure that your MongoDB instance is running and accessible.
Check that you have an Atlas account and have deployed a MongoDB database cluster. See Get Started with Atlas for information on how to login and create a cluster in Atlas.
- Windows
- macOS
- Linux
To make sure that your MongoDB instance is running on Windows, run the following command from the Windows command prompt:
If a mongod.exe
instance is running, you will
see something like:
To make sure your MongoDB instance is running on Mac, run the following command from your terminal:
If a mongod
instance is running, you will see
something like:
To make sure your MongoDB instance is running on Linux, run the following command from your terminal:
If a mongod
instance is running, you will see
something like:
Procedure¶
Read Data with Embedded Fields and Comparison Operators¶
In this exercise, you will read data using comparison operators.
Connect to your MongoDB instance.¶
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
Select the operating system platform on which you are running the MongoDB client you have selected.
- Windows
- macOS
- Linux
Pass the URI to the mongo shell followed by the --password
option. You will then be prompted for your password.
Pass the URI to the mongo shell followed by the --password
option. You will then be prompted for your password.
Pass the URI to the mongo shell followed by the --password
option. You will then be prompted for your password.
If you wish to manually configure your Compass connection, load
Compass and select the New Connection
link. You will see a
form where you can enter connection information for MongoDB.
Atlas users can copy a URI string from the Atlas console into Compass. MongoDB Compass can detect whether you have a MongoDB URI connection string in your system clipboard and auto- populate the connection dialog from the URI.
See Set Up Atlas Connectivity for information on how to get the Atlas connection string URI into your copy buffer.
If Compass was already running when you copied the URI string, click the NEW CONNECTION button.

You will be prompted to populate the connection dialog. Click Yes.
You should then populate the password field with the proper password for your MongoDB user in the connection form.
Note
Errors related to connecting through Compass will appear in red at the top of the Connect screen.
It’s a good idea to put your connection code in a class so that it can be reused.
If your connection_string
starts with mongodb+srv, you need to install the dnspython module with
Now add code to call the class you just created.
For the MongoDB java driver 3.7 and beyond, use the MongoClients.create()
method.
For legacy drivers (prior to 3.7), use:
The MongoDB.Bson
package is used in CRUD operations, so
you’ll import it here.
Replace your password and any parameters surrounded by $[]
in the connection string in the code below.
For now, you will use the context.TODO().
Later you’ll configure the context specific to your requirements.
You won’t know if the connection has been successful until you
use the connection. A ping is one way you can test the
connection. This is a full example of a Go connection to
mongoDB, including a test ping
.
In your Go workspace and project folder, run build.
Now run the binary. For binaries that are not installed, you’ll have to specify the path.
If you’d like to run the resulting binary without specifying a path, install the binary you just built into your Go workspace.
Now run the code. “yourprojectname” is the name of the project
directory that contains the file with your main()
function.
For installed binaries use:
For binaries that are not installed, you’ll have to specify the path.
The default timeout for the Go driver to connect to the database is 30 seconds. In the event that you are unable to connect, you will see an error that resembles this:
Switch to the test
database.¶
Switch to the database you wish
to query. In this case we will be using
test
.
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
To switch to the test
database in the mongo
shell, type
If the database has not been created already, click the Create Database button.

Select the test
database on the left side of the Compass
interface. Compass will list all of the collections in the
database below the database name.

To access the test
database:
Switch to the test
database and
access the inventory
collection.
Within the connect block, set db
to the test
database.
To access the test
database:
Switch to the test
database and
access the inventory
collection.
To access the test
database:
Select documents using the less-than operator.¶
The following example retrieves all documents from the inventory
collection where the size.h
field is less than 15. MongoDB uses
dot notation to specify fields within
embedded documents. size.h
refers to the h
field in the
size
document.
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
Copy the following filter into the Compass query bar and click Find:
First you will need to create the MongoCollection object you would like to query against.
Next pass the query document to the collection.find()
method.
For completeness, this is how you might wrap this call and run it with the asyncio event loop.
Iterate over the results.¶
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
By default, the shell will only show the first 20 documents and return a cursor. This is adequate when the result set only contains a few documents.
If your result set is larger, to see all of the results of your query, iterate the cursor.
Note
You can also manually iterate through the results by
typing it
when prompted by the shell.
You will see a list of all of the documents that match your criteria in the query window.
You can implement a java.util.function.Consumer
to print the
results of the iteration
Then iterate the cursor for documents, passing the
printConsumer
as a parameter.
In the code snippet above you may have noticed the code that iterates the results and prints them to the command line:
Iterate the results and print them to the command line:
Read Data with Compound Queries¶
Now you will read data from MongoDB using AND and OR logic to form compound queries.
Write an implied AND query.¶
To write a compound query in MongoDB that matches all of the query predicates (i.e. a logical AND), specify all of the fields that you wish to match in your find document. By default, MongoDB matches all of the fields.
The following example retrieves all documents in the inventory
collection where the status
equals "A"
and qty
is less
than ($lt
) 30
:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
Copy the following filter into the Compass query bar and click Find:
For completeness, this is how you might wrap this call and run it with the asyncio event loop.
MongoDB also provides a $and
logical operator as part of
its logical query operators, but the “implied AND” described above is
a more common pattern.
Iterate over the results.¶
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
This query does not require cursor iteration in mongo
shell
because the shell returns up to 20 results.
You will see a list of all of the documents that match your criteria in the query window.
You can implement a com.mongodb.Block
to print the results
of the iteration
Then iterate the cursor for documents, passing the
printBlock
as a parameter.
In the code snippet above you may have noticed the code that iterates the results and prints them to the command line:
Check your results.¶
If you have loaded data into your test database, you will see one or
more JSON documents returned. Your results should look something like
the JSON below. Note that the record below has a status
of "A"
and a qty
less than 30
per the criteria in the compound query.
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other

Write an “or” query.¶
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
Using the $or
query operator, specify a
compound query that joins each clause with a logical OR
conjunction so that the query selects the documents in the
collection that match at least one condition.
Using the $or
query operator, specify a
compound query that joins each clause with a logical OR
conjunction so that the query selects the documents in the
collection that match at least one condition.
Using the query operator, specify a
compound query that joins each clause with a logical OR
conjunction so that the query selects the documents in the
collection that match at least one condition.
Using the query operator, specify a
compound query that joins each clause with a logical OR
conjunction so that the query selects the documents in the
collection that match at least one condition.
Using the query operator, specify a
compound query that joins each clause with a logical OR
conjunction so that the query selects the documents in the
collection that match at least one condition.
Using the query operator, specify a
compound query that joins each clause with a logical OR
conjunction so that the query selects the documents in the
collection that match at least one condition.
Using the Or filter method, specify a
compound query that joins each clause with a logical OR
conjunction so that the query selects the documents in the
collection that match at least one condition.
The following example retrieves all documents in the collection where
the status
equals "A"
or qty
is less than
30
:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
Copy the following filter into the Compass query bar and click Find:
For completeness, this is how you might wrap this call and run it with the asyncio event loop.
Iterate over the results.¶
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
By default, the shell will only show the first 20 documents and return a cursor. This is adequate when the result set only contains a few documents.
If your result set is larger, to see all of the results of your query, iterate the cursor.
Note
You can also manually iterate through the results by
typing it
when prompted by the shell.
You will see a list of all of the documents that match your criteria in the query window.
You can implement a java.util.function.Consumer
to print the
results of the iteration
Then iterate the cursor for documents, passing the
printConsumer
as a parameter.
In the code snippet above you may have noticed the code that iterates the results and prints them to the command line:
Iterate the results and print them to the command line:
Retrieving Data with More Than One Compounding Clause¶
Now you will retrieve data from MongoDB using AND and OR logic together to form compound queries.
Write an implied AND query with an “or” clause.¶
In the following example, the compound query document selects all
documents in the collection where the status
equals "A"
and either qty
is less than 30 or
item
starts with the character p
:
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
Copy the following filter into the Compass query bar and click Find:
For completeness, this is how you might wrap this call and run it with the asyncio event loop.
Note
MongoDB supports regular expressions to perform string pattern matches.
Iterate over the results.¶
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
This query does not require cursor iteration in mongo
shell
because the shell returns up to 20 results.
You will see a list of all of the documents that match your criteria in the query window.
You can implement a com.mongodb.Block
to print the results
of the iteration
Then iterate the cursor for documents, passing the
printBlock
as a parameter.
In the code snippet above you may have noticed the code that iterates the results and prints them to the command line:
Summary¶
Congratulations! If you have successfully completed this guide, you have read data from MongoDB using MongoDB query operators and compound queries.