Query and Projection Operators in MongoDB

Priyanka Patwal
Last Updated: May 13, 2022

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.

 

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

Query operators

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.

1.) Comparison operators

To compare values in a document, MongoDB comparison operators can be utilized. The comparison operators are shown in the table below.

2.) 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:

Let’s see one example of all the above logical operators.

a.) $and operator

 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}}]})

 

b.) $or and $nor Operators

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"}]})

 

c.) $not operator

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}}})

 

 3.) Element Operators

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

The current element operators are listed in the table below.

Let’s see one example of each.

a.) $exists operator

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

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

 

b.) $type Operator

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"}})

 

4.) 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.

Let’s see one example of each.

a.) $jsonSchema Operator

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 } ] } )

 

b.) $mod Operator

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]}})

 

c.) $regex Operator

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

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

 

d.) $text Operator

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"}})

 

e.) $where Operator

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; }})

 

5.) Array Operators

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

Let’s see one example of each.

a.) $all operator

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

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

 

b.) $size operator

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

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

 

6.) 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 Operator

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

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

7.) Projection Operators

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

a.) $ Operator

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"}).

 b.) $elemMatch

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 } } } ) 

 

c.) $meta

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

{ $meta: <metaDataKeyword> }  

 

d.) $slice

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.

Frequently Asked Questions

1.) What is the difference between a collection and a table?

Ans: 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.

 

2.) What is an operator in MongoDB?

Ans: 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.

 

3.) What is MongoDB projection?

Ans: 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.

Key takeaways

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. 

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!!

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think