MongoDB Operators

MongoDB provides a wide range of intuitive operators that help us to query the collections for the relevant documents. The major categories and some examples are explained in the below article. Query operators are used to filter documents based on specific criteria. They are analogous to SQL's WHERE clause but are much more powerful and flexible, allowing for complex and nuanced queries. MongoDB query operators can be broadly classified into different categories:

1. Comparison Operators (`$eq`, $gt, $lt, $gte, $lte, $ne, etc.)

2. Logical Operators (`$and`, $or, $not, $nor)

3. Element Operators (`$exists`, $type)

4. Array Operators (`$in`, $nin, $all, $size, $elemMatch)

5. Evaluation Operators (`$regex`, $expr, $mod, $text)

6. Geospatial Operators (`$geoWithin`, $geoIntersects, $near)

7. Bitwise Operators (`$bitsAllClear`, $bitsAnySet)

8. Projection Operators (`$`, $elemMatch, $slice)

Let's see the most commonly used 1-5 query operators here.

1. Comparison Operators

a. $eq (Equal)

This operator matches documents where the value of a field equals the specified value.

Example:

Find documents where the status is "active".

db.users.find({ "status": { "$eq": "active" } })        

b. $gt (Greater Than)

This operator matches documents where the value of a field is greater than the specified value.

Example:

Find documents where the age is greater than 25.

db.users.find({ "age": { "$gt": 25 } })        

c. $gte (Greater Than or Equal)

This operator matches documents where the value of a field is greater than or equal to the specified value.

Example:

Find documents where the age is greater than or equal to 18.

db.users.find({ "age": { "$gte": 18 } })        

d. $lt (Less Than)

This operator matches documents where the value of a field is less than the specified value.

Example:

Find documents where the age is less than 30.

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

e. $lte (Less Than or Equal)

This operator matches documents where the value of a field is less than or equal to the specified value.

Example:

Find documents where the age is less than or equal to 21.

db.users.find({ "age": { "$lte": 21 } })        

f. $ne (Not Equal)

This operator matches documents where the value of a field is not equal to the specified value.

Example:

Find documents where the status is not "inactive".

db.users.find({ "status": { "$ne": "inactive" } })        

2. Logical Operators

a. $and

This operator joins query clauses with a logical AND, returning all documents that match the conditions of both clauses.

Example:

Find documents where the age is greater than 18 and the status is "active".

db.users.find({ "$and": [{ "age": { "$gt": 18 } }, { "status": "active" }] })        

b. $or

This operator joins query clauses with a logical OR, returning all documents that match the conditions of either clause.

Example:

Find documents where the status is either "active" or the age is less than 20.

db.users.find({ "$or": [{ "status": "active" }, { "age": { "$lt": 20 } }] })        

c. $not

This operator inverts the effect of a query expression and returns documents that do not match the query.

Example:

Find documents where the age is not greater than 18.

db.users.find({ "age": { "$not": { "$gt": 18 } } })        

3. Array Operators

a. $in

This operator matches any of the values specified in an array.

Example:

Find documents where the status is either "active", "pending", or "banned".

db.users.find({ "status": { "$in": ["active", "pending", "banned"] } })        

b. $nin

This operator matches none of the values specified in an array.

Example:

Find documents where the status is neither "inactive" nor "banned".

db.users.find({ "status": { "$nin": ["inactive", "banned"] } })        

4. Element Operators

a. $exists

This operator matches documents that have the specified field.

Example:

Find documents where the email field exists.

db.users.find({ "email": { "$exists": true } })        

b. $type

This operator matches documents where the field is of the specified BSON type.

Example:

Find documents where the age field is of type integer.

db.users.find({ "age": { "$type": "int" } })        

5. Evaluation Operators

a. $regex

This operator matches documents where the value of a field matches a specified regular expression.

Example:

Find documents where the username starts with "user".

db.users.find({ "username": { "$regex": "^user" } })        

b. $expr

This operator allows the use of aggregation expressions within the query language.

Example:

Find documents where the spent amount is greater than the budget.

db.expenses.find({ "$expr": { "$gt": ["$spent", "$budget"] } })        

Knowing these basic functionalities will help in solving complex queries.

Building Complex Queries

Complex queries in MongoDB involve combining multiple query operators and conditions. Here's how to build them step by step:

1. Basic Query

Find documents where the age is greater than 30 and the status is "active".

db.users.find({
  "age": { "$gt": 30 },
  "status": "active"
})        

This query will return documents that match both conditions.

2. Using Logical Operators

Logical operators like $and, $or, and $not are used to combine multiple conditions.

Find documents where either status is "active" or the age is less than 20.

db.users.find({
  "$or": [
    { "status": "active" },
    { "age": { "$lt": 20 } }
  ]})        

Using $and:

Find documents where age is greater than 30 and status is "active".

db.users.find({
  "$and": [
    { "age": { "$gt": 30 } },
    { "status": "active" }
  ]
})        

Using $not:

Find documents where the age is not greater than 18.

db.users.find({
  "age": { "$not": { "$gt": 18 } }
})        

3. Combining Logical and Comparison Operators

You can nest logical operators within comparison operators to create more complex queries.

Find documents where the age is either less than 20 or between 30 and 40, and the status is not "inactive".

db.users.find({  
"$and": [
    {
      "$or": [
        { "age": { "$lt": 20 } },
        { "age": { "$gte": 30, "$lte": 40 } }
      ]
    },
    { "status": { "$ne": "inactive" } }
  ]
})        

4. Working with Arrays

When working with arrays, MongoDB offers powerful operators to match documents based on the contents of arrays.

Find documents where the tags array contains either "mongodb" or "database".

Using $in:

db.articles.find({
  "tags": { "$in": ["mongodb", "database"] }
})        

Using $elemMatch:

Find documents where the scores array contains at least one element greater than 80 and less than 90.

db.students.find({
  "scores": { "$elemMatch": { "$gt": 80, "$lt": 90 } }
})        

5. Using the $expr Operator

The $expr operator allows you to use aggregation expressions within queries. It can be particularly useful when you need to compare fields within the same document.

Find documents where the spent amount is greater than the budget.

db.expenses.find({
  "$expr": { "$gt": ["$spent", "$budget"] }
})        

6. Combining Multiple Queries

You can build even more complex queries by combining multiple conditions with different logical operators.

Find documents where the status is "active", age is greater than 25, or the city is "New York", and the email field exists.

db.users.find({
  "$and": 
    {
      "$or": [
        { "status": "active" },
        { "age": { "$gt": 25 } },
        { "city": "New York" }
      ]
    },
    { "email": { "$exists": true } }
  ]
})        

Tips for Building Complex Queries

1. Start Simple: Begin by writing simple queries to filter one or two fields. Gradually add complexity by including logical and comparison operators.

2. Leverage Indexes: Make sure to use indexes on fields that are frequently queried, especially in complex queries, to improve performance.

3. Use Query Operators Together: Combine different query operators creatively to express the exact criteria you need.

Test and then proceed. Build from the inside query and then build the outside query and the projection.

By mastering MongoDB query operators and understanding how to build complex queries, you can effectively retrieve and manipulate data in your MongoDB collections.


Shrey Batra

CEO @ Cosmocloud | Ex-LinkedIn | Angel Investor | MongoDB Champion | Book Author | Patent Holder (Distributed Algorithms)

6 个月

Amazing examples in this article Preethi Pattabiraman ?? MongoDB

要查看或添加评论,请登录

Preethi Pattabiraman的更多文章

  • Switch-Case

    Switch-Case

    There is nothing that helps a developer like a switch case statement. With multiple conditions and business logic to…

    2 条评论
  • Java Integer Cache

    Java Integer Cache

    I was astounded to learn about this feature in Java called the IntegerCache. A new functionality was added to reduce…

  • Circuit Breaker

    Circuit Breaker

    A microservice always needs its friends, the supporting microservices. They all collaborate to make an application…

    1 条评论
  • REST API - Content Negotiation

    REST API - Content Negotiation

    Please find part 1 of this series in the above link. Generally, REST resources can have multiple representations of the…

    1 条评论
  • REST API - Documentation

    REST API - Documentation

    There are some basic REST API features that are expected from any API, such as Documentation Content Negotiation I18N…

    9 条评论
  • Finally

    Finally

    Many of the interview questions are aimed to make us pause. But, if you note those little pointers, it will be a…

社区洞察

其他会员也浏览了