Table of contents
1.
Introduction
2.
What is MongoDB Query operators?
3.
MongoDB Comparison operators
3.1.
$eq
3.1.1.
Syntax
3.1.2.
Example
3.2.
$gt
3.2.1.
Syntax
3.2.2.
Example
3.3.
$lt
3.3.1.
Syntax
3.3.2.
Example
3.4.
$gte
3.4.1.
Syntax
3.4.2.
Example
3.5.
$lte
3.5.1.
Syntax
3.5.2.
Example
3.6.
$in
3.6.1.
Syntax
3.6.2.
Example
3.7.
$ne
3.7.1.
Syntax
3.7.2.
Example
3.8.
$nin
3.8.1.
Syntax
3.8.2.
Example
4.
MongoDB Logical Operators
4.1.
$and 
4.1.1.
Syntax
4.1.2.
Example
4.2.
$or and $nor
4.2.1.
Syntax for $or
4.2.2.
Syntax for $nor
4.2.3.
Example
4.3.
$not
4.3.1.
Syntax
4.3.2.
Example
5.
MongoDB Element Operators
5.1.
$exists
5.1.1.
Syntax
5.1.2.
Example
5.2.
$type
5.2.1.
Syntax
5.2.2.
Example
6.
MongoDB Evaluation Operators
6.1.
$jsonSchema
6.1.1.
Syntax
6.1.2.
Example
6.2.
$mod 
6.2.1.
Syntax
6.2.2.
Example
6.3.
$regex 
6.3.1.
Syntax
6.3.2.
Example
6.4.
$text
6.4.1.
Syntax
6.4.2.
Example
6.5.
$where
6.5.1.
Syntax
6.5.2.
Example
7.
MongoDB Array Operators
7.1.
$all 
7.1.1.
Syntax
7.1.2.
Example
7.2.
$size
7.2.1.
Syntax
7.2.2.
Example
8.
MongoDB Comment Operator
8.1.
$comment
8.1.1.
Syntax
8.1.2.
Example
9.
MongoDB Projection Operators
9.1.
$ Operator
9.1.1.
Syntax
9.1.2.
Example
9.2.
$elemMatch
9.2.1.
Syntax
9.2.2.
Example
9.3.
$meta
9.3.1.
Syntax
9.3.2.
Example
9.4.
$slice
9.4.1.
Syntax
9.4.2.
Example
10.
Frequently Asked Questions
10.1.
What is the difference between a collection and a table?
10.2.
What is an operator in MongoDB?
10.3.
What is MongoDB projection?
10.4.
What is the $[] operator in MongoDB?
11.
Conclusion
Last Updated: Mar 27, 2024
Easy

MongoDB Query and Projection Operators

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

MongoDB provides many different operators for interacting with the database. Operators are special symbols or keywords that tell a compiler or interpreter what mathematical or logical operations to perform.

MongoDB Query and Projection Operators

Here we'll learn query and projection operators. So let's get going!

What is MongoDB Query operators?

MongoDB is a NoSQL database that stores data in flexible, JSON-like documents, offering high scalability and performance for modern applications. It features a flexible data model, powerful query language, and horizontal scalability through sharding, making it ideal for handling large volumes of unstructured or semi-structured data.

The query operators extend MongoDB's capabilities by allowing developers to write complicated queries that interact with data sets relevant to their applications.

MongoDB offers the following query operator types:

  • Comparison
  • Logical
  • Element
  • Evaluation
  • Geospatial
  • Array
  • Bitwise
  • Comments
     

Now, let's dive deeper into these operators.

MongoDB Comparison operators

To compare values in a document, Mongodb comparison operators can be utilized. These are some comparison operators:

$eq

Matches values that are equal to a specified value.

Syntax

{ field: { $eq: value } }

Example

{ age: { $eq: 30 } }

$gt

Matches values that are greater than a specified value.

Syntax

{ field: { $gt: value } }

Example

{ score: { $gt: 80 } }

$lt

Matches values that are less than a specified value.

Syntax

{ field: { $lt: value } }

Example

{ price: { $lt: 100 } }

$gte

Matches values that are greater than or equal to a specified value.

Syntax

{ field: { $gte: value } }

Example

{ quantity: { $gte: 10 } }

$lte

Matches values that are less than or equal to a specified value.

Syntax

{ field: { $lte: value } }

Example

{ rating: { $lte: 5 } }

$in

Matches any of the values specified in an array.

Syntax

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

Example

{ color: { $in: ["red", "blue", "green"] } }

$ne

Matches all values that are not equal to a specified value.

Syntax

{ field: { $ne: value } }

Example

{ status: { $ne: "inactive" } }

$nin

Matches none of the values specified in an array.

Syntax

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

Example

{ category: { $nin: ["electronics", "clothing"] } }

MongoDB Logical Operators

Logical operators in MongoDB can be used to filter data based on certain criteria. Multiple conditions can be combined using these operators. Each operator assigns a true or false value to the specified condition.

The logical operators in MongoDB are listed below:

$and 

Performs a logical AND operation on an array of two or more expressions.

Syntax

{ $and: [ { expression1 }, { expression2 }, ... ] }

Example

To find documents that satisfy both the following conditions

  • designation is equal to "Software Developer".
  • empAge is between 20 and 35
db.employees.find({ $and: [{"designation ": "Software Developer"}, {"emp_age": {$gte: 20, $lte: 35}}]})

 

$or and $nor

$or performs a logical OR operation while $nor performs a logical NOR (NOT OR) operation on an array of two or more expressions.

Syntax for $or

{ $or: [ { expression1 }, { expression2 }, ... ] }

Syntax for $nor

{ $nor: [ { expression1 }, { expression2 }, ... ] }

Example

To find documents that satisfy either of the following conditions.

  • designation is equal to "SDE1" or "SDE2".
db.employees.find({ $or: [{"designation ": "SDE1"}, {"designation ": "SDE2"}]})

 

To find documents that do not satisfy either of the following conditions.

  • designation is equal to "SDE1" or "SDE2".
db.employees.find({ $nor: [{"designation": "SDE1"}, {"designation": "SDE2"}]})

 

$not

Performs a logical NOT operation on the specified expression.

Syntax

{ field: { $not: { expression } } }

Example

To find documents where they do not match the given conditions.

  • empAge is not greater than or equal to 35
db.employees.find({ "empAge": { $not: { $gte: 35}}})

 

MongoDB Element Operators

The element query operators are used to find documents based on the document's fields. 

$exists

Checks if a field exists or not in a document.

Syntax

{ field: { $exists: true/false } }

Example

To find documents where the empAge field exists and is greater than equal to 30.

db.employees.find({ "empAge": { $exists: true, $gte: 30}})

 

$type

Matches documents where the value of a field is of the specified type.

Syntax

{ field: { $type: "type" } }

Example

The following query statement returns documents if the emp_age field is a double type. If we specify an alternative data type, no records will be returned even though the field exists because it does not correlate to the relevant field type.

db.employees.find({ "empAge": { $type: "double"}})

 

MongoDB Evaluation Operators

The MongoDB evaluation operators can assess a document's overall data structure as well as individual fields. Because these operators might be considered advanced MongoDB capabilities, we are merely looking at their fundamental functionality. 

The following is a list of MongoDB's most popular evaluation operators.

$jsonSchema

Validates documents against the specified JSON Schema.

Syntax

{ $jsonSchema: { schema } }

Example

To find documents that correspond to the following JSON schema in the testdata collection.

Syntax: { $jsonSchema: <JSON Schema object> }

We’ll create the following collection named students and use the $jsonSchema operator to set schema validation rules:

Student Collection:

db.createCollection("students", {
  validator: {
      $jsonSchema: {
        bsonType: "object",
        required: [ "name", "year", "major", "address" ],
        properties: {
            name: {
              bsonType: "string",
              description: "must be a string and is required"
            },
            year: {
              bsonType: "int",
              minimum: 2017,
              maximum: 3017,
              description: "must be an integer in [ 2017, 3017 ] and is required"
            },
            major: {
              enum: [ "Math", "English", "Computer Science", "History", null ],
              description: "can only be one of the enum values and is required"
            },
            gpa: {
              bsonType: [ "double" ],
              description: "must be a double if the field exists"
            },
            address: {
              bsonType: "object",
              required: [ "city" ],
              properties: {
                  street: {
                    bsonType: "string",
                    description: "must be a string if the field exists"
                  },
                  city: {
                    bsonType: "string",
                    "description": "must be a string and is required"
                  }
              }
            }
        }
      }
  }
})

 

Now, we’ll define the sample schema object as:

let myschema =  {
      required: [ "item", "qty", "instock" ],
      properties: {
        item: { bsonType: "string" },
        qty: { bsonType: "int" },
        size: {
            bsonType: "object",
            required: [ "uom" ],
            properties: {
              uom: { bsonType: "string" },
              h: { bsonType: "double" },
              w: { bsonType: "double" }
            }
          },
          instock: { bsonType: "bool" }
      }
}

 

Now, we can use $jsonSchema operator as follows:

  • Using the $jsonSchema to find all documents in the collection that satisfy the schema:
db.inventory.find( { $jsonSchema: myschema } )
db.inventory.aggregate( [ { $match: { $jsonSchema: myschema } } ] )

 

  • Using the  $jsonSchema with the $nor to find all documents that do not satisfy the schema:
db.inventory.find( { $nor: [ { $jsonSchema: myschema } ] } )

 

  • Updating all documents that do not satisfy the schema:
db.inventory.updateMany( { $nor: [ { $jsonSchema: myschema } ] }, { $set: { isValid: false } } )

 

  • Deleting all documents that do not satisfy the schema:
db.inventory.deleteMany( { $nor: [ { $jsonSchema: myschema } ] } )

 

$mod 

Performs a modulo operation on the value of a field and selects documents with the specified result.

Syntax

{ field: { $mod: [ divisor, remainder ] } }

Example

To find documents where the remainder is 1000 when divided by 3000 in the inventory collection, we use the following:

db.inventory.find({"quantity": {$mod: [3000, 1000]}})

 

$regex 

Selects documents where values match a specified regular expression pattern.

Syntax

{ field: { $regex: "pattern", $options: "options" } }

Example

To find documents that contain the word "employee" in the name field in the inventory collection.

db.inventory.find({"name": {$regex: '.employee.'}})

 

$text

Performs a text search on string fields.

Syntax

{ $text: { $search: "searchString" } }

Example

To find documents by using a text search for "Non-CS" in the branch field. If the field is not indexed, we should create a text index before searching.

db.inventory.createIndex({ "branch": "text"})
db.inventory.find({ $text: { $search: "Mon-CS"}})

 

$where

Matches documents based on JavaScript expression.

Syntax

{ $where: "JavaScript expression" }

Example

To find documents from the "employee" collection where the empid field is a string type and is equal to the given md5 hash specified by the JavaScript function.

db.employee.find({ $where: function() { var strvalue = isString(this.empid ) && hex_md5(this._id) == '57fee1331906c3a8f0fa583d37ebbea9'; return value; }})

 

MongoDB Array Operators

Array operators in MongoDB are used to query documents that include arrays. MongoDB provides the following array operators.

$all 

Matches arrays that contain all elements specified in the query.

Syntax

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

Example

To find documents where the category array field contains "Web-dev" and "MachineLearning" values.

db.inventory.find({ "category": { $all: ["Web_dev", "MachineLearning"]}})

 

$size

Matches arrays with a specific number of elements.

Syntax

{ field: { $size: sizeValue } }

Example

To find documents where the category array field has two elements.

db.inventory.find({ "category": { $size: 2}})

 

MongoDB Comment Operator

A comment is associated with an expression that takes a query predicate when using the MongoDB comment query operator. Adding comments to queries makes it easier for database managers to monitor and analyze MongoDB logs.

$comment

Adds a comment to a query.

Syntax

{ $comment: "commentString" }

Example

The following example adds a $comment to a find() operation:

db.records.find(
  {
    x: { $mod: [ 2, 0 ] },
    $comment: "Find even values."
  }
)

MongoDB Projection Operators

MongoDB Projection Operators enable users to control which fields are returned in the query results. These operators allow for the exclusion or inclusion of specific fields, including fields within embedded documents or arrays. They enhance query performance by reducing network overhead and improving readability by focusing only on relevant data. 

Some of the important projection operators of MongoDB are given below.

$ Operator

Projects the first element in an array that matches the query condition.

Syntax

{ field: { $: condition } }

Example

The $ operator restricts the contents of a query result array to only the first member that matches the query document.

db.promo.find({ "period": { $eq: 7}, $comment: "Find Weeklong tests"}).

$elemMatch

Selects documents if the array field contains at least one element that matches all the specified query criteria.

Syntax

{ field: { $elemMatch: { criteria } } }

Example

Using this operator, the content of the array field from the query result is confined to the first element matching the element $elemMatch condition.

db.library.find( { bookcode: "60109" }, { students: { $elemMatch: { roll: 103 } } } ) 

 

$meta

Returns metadata associated with text search results.

Syntax

{ $meta: "metadataField" }

Example

The meta operation delivers a response for each document that matches the query in terms of metadata.

{ $meta: <metaDataKeyword> }  

 

$slice

Limits the number of elements in an array that is returned in the query results.

Syntax

{ field: { $slice: number } }

Example

This operator controls the number of values in an array that a query returns.

db.books.find( { field: value }, { array: {$slice: count } } );  

 

This was all about projection and Query operators of MongoDB.

Read about Bitwise Operators in C here.

Frequently Asked Questions

What is the difference between a collection and a table?

A MongoDB database stores data in collections rather than tables. Records or rows in a relational database table are equivalent to documents. Fields are analogous to columns in a relational database table, and each document has one or more of them.

What is an operator in MongoDB?

Operators are special symbols or keywords that tell a compiler or interpreter what mathematical or logical operations to perform. The query operators extend MongoDB's capabilities by allowing developers to write complicated queries that interact with data sets that are relevant to their applications.

What is MongoDB projection?

In MongoDB, projection refers to picking only the data that is required rather than the entire document's data. If a document has five fields and you only want to show three of them, projection helps us do it.

What is the $[] operator in MongoDB?

The $[] operator, also known as the all positional operator, is used to update all elements in an array that match the specified conditions in an update operation in MongoDB. 

Conclusion

We learned that MongoDB provides a wide range of operators and projectors which help interact with the database. These operators include comparison, logical, element operators, etc. 

Recommended Reading:

If you wish to learn more about MongoDB, here’s an amazing article on Introduction to MongoDB and Creating Database, Collections and Documents in MongoDB.

Happy learning!!

 

Live masterclass