Read Data using Operators and Compound Queries
Overview
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
What You'll Need
A connection string to your MongoDB deployment.
Sample datasets loaded into your cluster.
Procedure
Read Data with Embedded Fields and Comparison Operators
In this exercise, you will read data using comparison operators.
Select documents using the less-than operator.
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).
Read Data with Compound Queries
Now you will read data from MongoDB using AND and OR logic to form compound queries.
Write an 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. 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
.
Write an OR query.
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.
Summary
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.