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.planetscollection 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.
Use dot notation
in this query to select documents where the embedded document
has a value in its
mean field less than 15 degrees (Celsius).
Now you will read data from MongoDB using AND and OR logic to form compound queries.
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
collection where the
surfaceTemperatureC.mean field is less than
surfaceTemperatureC.min field is greater than
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
7 AND less than
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.