Do you think IIT Guwahati certified course can help you in your career?
No
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!
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.
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.
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.
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"
}
}
}
}
}
}
})
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.
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.
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:
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.
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.