Docs Menu

Docs HomeStart with Guides

Read Data using Operators and Compound Queries

In the previous read guide, Read Data from MongoDB With Queries, you read data using equality queries. In this guide, you will:

  • Read data from the sample_guides.planets collection with MongoDB's comparison operators.

  • Combine query criteria to make compound queries.

  • Use dot notation to query embedded fields.

Time required: 20 minutes

In this exercise, you will read data using comparison operators.

1
2

Use dot notation in this query to select documents where the embedded document surfaceTemperatureC has a value in its mean field less than 15 degrees (Celsius).

3

Here is the complete code followed by sample output. Results have been truncated for display purposes.

Now you will read data from MongoDB using AND and OR logic to form compound queries.

1

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. If you followed the previous guide you've already done this!

The following example retrieves all documents in the planets collection where the surfaceTemperatureC.mean field is less than 15 and the surfaceTemperatureC.min field is greater than -100.

2

OR queries are required when you want to specify criteria that are mutually exclusive. For example, you can't match documents in the planets collection where the orderFromSun value is both greater than 7 AND less than 2.

The following example shows how to use the $or operator to express mutually exclusive criteria.

If you have successfully completed this guide, you have read data from MongoDB using MongoDB query operators and compound queries.

You can combine query operators in almost limitless ways to express complex queries. For example, you could query for documents that have rings AND a specific chemical compound in their atmosphere, or that are a specific temperature, AND all have the letter 'E' in their name.

In the next guide, you'll learn how to insert data into MongoDB.

What's Next
Insert Data into MongoDB
15 mins

Create and insert documents into 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
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.