Published on

Understanding Basic MongoDB Operators

Authors
  • avatar
    Name
    Hieu Cao
    Twitter

Introduction

MongoDB provides a wide range of query operators to filter and manipulate data. In this blog, we'll explore six essential operators—$eq, $ne, $gt, $lt, $in, and $nin. These operators allow you to construct precise queries for retrieving data from collections.


Prerequisites

Before proceeding, ensure you have:

  • MongoDB installed and running.
  • Access to the MongoDB shell or a database management tool.
  • A basic understanding of MongoDB documents and collections.

1. $eq - Equal

The $eq operator matches documents where the field is equal to a specified value.

Syntax:

{
  field: {
    $eq: value
  }
}

Example:

Retrieve users aged 30:

> db.users.find({ age: { $eq: 30 } });

2. $ne - Not Equal

The $ne operator matches documents where the field is not equal to a specified value.

Syntax:

{
  field: {
    $ne: value
  }
}

Example:

Retrieve users not aged 30:

> db.users.find({ age: { $ne: 30 } });

3. $gt - Greater Than

The $gt operator matches documents where the field is greater than a specified value.

Syntax:

{
  field: {
    $gt: value
  }
}

Example:

Retrieve users older than 30:

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

4. $lt - Less Than

The $lt operator matches documents where the field is less than a specified value.

Syntax:

{
  field: {
    $lt: value
  }
}

Example:

Retrieve users younger than 30:

> db.users.find({ age: { $lt: 30 } });

5. $in - In

The $in operator matches documents where the field's value is in a specified array.

Syntax:

{ field: { $in: [value1, value2, ...] } }

Example:

Retrieve users aged 25, 30, or 35:

> db.users.find({ age: { $in: [25, 30, 35] } });

6. $nin - Not In

The $nin operator matches documents where the field's value is not in a specified array.

Syntax:

{ field: { $nin: [value1, value2, ...] } }

Example:

Retrieve users not aged 25, 30, or 35:

> db.users.find({ age: { $nin: [25, 30, 35] } });

Combining Operators

You can combine these operators to build complex queries. For example:

Retrieve active users older than 25 but not aged 40:

> db.users.find({
    isActive: true,
    age: { $gt: 25, $nin: [40] }
});

Conclusion

MongoDB's query operators like $eq, $ne, $gt, $lt, $in, and $nin are powerful tools for filtering data. By understanding how to use these operators, you can construct precise and efficient queries for your applications. Explore these examples further and try combining them to handle more advanced data retrieval scenarios.

Happy Coding!