Authors: @Jacqueline Osborn

Last Updated: 4/10/21

MongoDB has a wide range of operators to make it easier to fetch specific data. Some use cases for them would be if you want to filter your data on the backend or mass update fields in a collection. In this doc, we'll go over some of the more popular operators and how to use them.

Query Operators

These are for filtering! Below are some code examples of how you might effectively use these operators. MongoDB also has good documentation for more of these that are not included. They are very powerful!!!

Matching a specific value

Say I want to query my collection of users, for all users whose last name equals "Osborn". All I have to do is this:

db.users.find( { lastName: "Osborn" } );
// If you have a mongoose model, it might look like this:
User.find( { lastName: "Osborn" } );

Similarly, if I want to find all users who have "Harry Potter" listed as one of their books read, where booksRead is an array, you can do the same thing:

db.users.find( { booksRead: "Harry Potter" } );

Greater than ($gt)

Now, let's say I want to find all users that are above 20 years old 🤪. We can use the $gt operator!

db.users.find( { age: { $gt: 20 } } );

There are similar operators, such as $lt (less than), $gte, and $lte (greater/less than or equal).

In ($in)

The $in operator is helpful where you want to find data where fields can equal multiple different values (an array of values). In this example, we query for users that are either 18 or 21 years old.

db.users.find( { age: { $in: [18, 21] } } );

There is also an operator $nin, where the syntax is the same (except using $nin instead of $in), where it does the opposite - it finds everything from the collection where the field specified is not any of the values in the array.