Read Data from MongoDB With Queries
Overview
In the previous guide, Read Data in MongoDB, you retrieved all documents
from the sample_guides.planets
collection without specifying any
criteria that the documents should meet.
In this guide, you will query the collection and retrieve documents that match specific equality criteria, meaning the values of the specified field or fields must match.
Time required: 15 minutes
What You'll Need
A connection string to your MongoDB deployment.
Sample datasets loaded into your cluster.
Procedure
Connect to your MongoDB instance.
Tip
In this code block there is a comment to replace the connection URI with your own. Replace the URI string with your own Atlas connection string.
Retrieve specific documents in the planets
collection.
You can retrieve specific documents from a collection by applying a query filter.
A query filter is a document that contains the criteria you are searching for.
The following example illustrates using a query filter to retrieve documents
from the planets
collection that have a hasRings
field
with a value of true
.
Query using multiple criteria.
You can also query the collection using multiple criteria.
The following example illustrates using multiple criteria to retrieve
documents from the planets
collection that have a
hasRings
field with a value of false
and Argon(Ar)
as an
entry in the mainAtmosphere
field.
Even though the mainAtmosphere
field is an array, you can use
a strict equality query because MongoDB treats arrays as first-class
types. During execution of the query, MongoDB compared each entry
in the array to the value you specified, in this case "Ar"
,
to determine if the documents matched your criteria.
Summary
If you have completed this guide, you have retrieved data from MongoDB using specific equality criteria. This is useful when you know exactly what you're searching for, for example an item number, a username, or chemical element.
In the next guide, you'll learn how to read data from MongoDB using comparison operators to retrieve documents that match a broader set of criteria.
See Also
See the following resources for more in-depth information about the concepts presented here:
Use operators and compound queries to retrieve documents in MongoDB.