Docs Menu

Docs HomeStart with Guides

Read Data from MongoDB With Queries

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

1

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.

2

Switch to the database and collection you want to query. In this case you will use the sample_guides database and planets collection.

3

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.

4
5

Here is the complete code followed by sample output.

Note

Your ObjectId values will differ from those shown.

6

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.

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 the following resources for more in-depth information about the concepts presented here:

  • Specify Equality Condition

  • Match an Embedded or Nested Array

What's Next
Read Data using Operators and Compound Queries
20 mins

Use operators and compound queries to retrieve documents in MongoDB.

Start Guide
Chapter 2
CRUD
  • Add a MongoDB Driver
  • Read Data in MongoDB
  • Read Data from MongoDB With Queries
  • Read Data using Operators and Compound Queries
  • Insert Data into MongoDB
  • Update Data in MongoDB
  • Delete Data from MongoDB
Start with Guides →