MongoDB

MongoDB Query

When using most MongoDB CRUD operations, we will need a filter that allows us to narrow down the set of matched documents before executing the operations, these filters are called query documents.

In a query document, you can match fields against literal values (e.g. { title: "The Room"}) or you can compose query operators to express more complex matching criteria. In this guide, we cover the following categories of query operators in MongoDB which are most used by developers and show examples on how to use them:


Literal Value Queries

Literal value queries allow you to query for data that exactly matches a value you provide in the query document. A literal value query has two parts: a field name and a value. Documents returned from such a query must contain a field that has exactly the same name as the provided name and a value for that field that is exactly the same as the provided value. The following operation uses a literal query to search for documents containing a field called "name" that has a value of "apples":

const query = { "name": "apples" };
const cursor = collection.find(query);
await cursor.forEach(console.dir);

// Console log results
{ "_id": 1, "name": "apples", "qty": 5, "rating": 3 }

Note

Literal value queries are equivalent to the $eq comparison operator.

collection.find({ rating: { $eq: 5 } })

is equivalent to

collection.find({ rating: 5 })

Comparison Operators

Comparison operators allow you to query for data based on comparisons with values in a collection. Common comparison operators include:

  • $gt for "greater than" comparisons
  • $gte for "greater than or equal" comparisons
  • $lt for "less than" comparisons
  • $lte for "less than or equal" comparisons
  • $ne for "not equal to" comparisons.
  • $in matches any of the values specified in an array
  • $nin matches none of the values specified in an array

The following operation uses the comparison operator $gt to search for documents with a quantity value greater than 5 and prints them out:

// $gt means "greater than"
const query = { qty: { $gt : 5 } };
const cursor = collection.find(query);
await cursor.forEach(console.dir);

// Example console log results
{ "_id": 2, "name": "bananas", "qty": 7, "rating": 1 }
{ "_id": 3, "name": "oranges", "qty": 6, "rating": 2 }

Note

For $in and $nin operators, if the comparing field is type Array, MongoDB will consider a document matched if the intersection of that field's value and criteria array is not empty.

Logical Operators

Logical operators allow you to query for data using logic applied to the results of field-level operators. Below are all the logical operators you can use:

  • $and joins query clauses and returns all documents that match the conditions of all clauses.
  • $or joins query clauses and returns all documents that match the conditions of either clause.
  • $nor joins query clauses and returns all documents that fail to match all clauses.
  • $not inverts the effect of a query expression and returns documents that do NOT match the query expression

The following operation uses the logical operator $not to search for documents with a quantity value that is not greater than 5 and prints them out:

const query = { qty: { $not: { $gt: 5 }}};
const cursor = collection.find(query);
await cursor.forEach(console.dir);


// Example console log result
{ "_id": 4, "name": "avocados", "qty": 3, "rating": 5 }
{ "_id": 1, "name": "apples", "qty": 5, "rating": 3 }

Note

If a query document contains multiple elements, those elements are combined together with an implicit $and logical operator by default. The following queries are equivalent:

collection.find({>
  rating: { $eq: 5 },
  qty: { $gt: 4 },
})
collection.find({
  $and: [
    { rating: { $eq: 5 } }, 
    { qty: { $gt: 4 } }
  ],
})

Element Operators

Element operators allow you to query based on the presence, absence of a field using $exists operator, or type of a field using $type operator. The following operation uses the element operator $exists to search for documents containing the microsieverts field:

const query = { microsieverts: { $exists: true } };
const cursor = collection.find(query);
await cursor.forEach(console.dir);

// Example console log result
{ "_id": 2, "name": "bananas", "qty": 7, "rating": 1, "microsieverts": 0.1 }

Evaluation Operators

Evaluation operators allow you to execute higher-level logic, like regex and text searches, when querying for documents in a collection. Common evaluation operators include $regex for searching values using Regular Expressions and $text to perform text search. The following operation uses the evaluation operator $mod to search for documents with a quantity value that is divisible by 3 with a remainder of 0:

// $mod means "modulo" and returns the remainder after division
const query = { qty: { $mod: [ 3, 0 ] } };
const cursor = collection.find(query);
await cursor.forEach(console.dir);

// Example console log result
{ "_id": 3, "name": "oranges", "qty": 6, "rating": 2 }
{ "_id": 4, "name": "avocados", "qty": 3, "rating": 5 }
Previous
CRUD Operations