MongoDB Operators

MongoDB operators are special symbols or keywords that unlock the power of your data. Just like a chef uses tools to prepare a meal, these operators help you find, modify, and analyze information stored in your MongoDB database. Mastering these operators empowers you to efficiently query, manipulate, and unlock the hidden insights within your data.

Comparison Operators

Find documents where age is greater than 30 in ‘users’ collection

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

Find documents where age is less than or equal to 28 in ‘users’ collection

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

Find documents where title is equal to “MongoDB Overview” in ‘posts’ collection

db.posts.find({ title: { $eq: "MongoDB Overview" } })

Find documents where age is not equal to 30 in ‘users’ collection

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

In these queries, we utilize the $gt (greater than), $lt (less than), and $eq (equality) comparison operators to filter documents based on specific criteria. Additionally, we demonstrate the $ne (not equal) operator to find documents where a field does not match a specified value.

Logical Operators

Find documents where age is greater than 25 AND less than 35 in ‘users’ collection

db.users.find({ $and: [ { age: { $gt: 25 } }, { age: { $lt: 35 } } ] })

Find documents where username is “johndoe” OR email is “janedoe@example.com” in ‘users’ collection

db.users.find({ $or: [ { username: "johndoe" }, { email: "janedoe@example.com" } ] })

Find documents where age is NOT equal to 30 in ‘users’ collection

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

Find documents where age is neither 30 nor 31 in ‘users’ collection

db.users.find({ age: { $nor: [ { $eq: 30 }, { $eq: 31 } ] } })

We use the $and operator to find documents where multiple conditions must be satisfied simultaneously. The $or operator is utilized to find documents where at least one of the specified conditions is met. Using the $not operator, we exclude documents where a specific condition is true. The $nor operator is used to find documents where none of the specified conditions are met.

Arithmetic Operators

Add 5 to the age of all users in ‘users’ collection

db.users.updateMany({}, { $add: { age: 5 } })

Subtract 2 from the age of users aged 30 in ‘users’ collection

db.users.updateMany({ age: 30 }, { $subtract: { age: 2 } })

Multiply the age of users by 2 in ‘users’ collection

db.users.updateMany({}, { $multiply: { age: 2 } })

Divide the age of all users by 2 in ‘users’ collection

db.users.updateMany({}, { $divide: { age: 2 } })

Calculate the absolute value of the age of all users in ‘users’ collection

db.users.updateMany({}, { $abs: { age: true } })

We use the $add, $subtract, $multiply, and $divide operators to perform addition, subtraction, multiplication, and division respectively on numeric fields. The $abs operator calculates the absolute value of numeric fields.

Field Update Operators

Update the age of users to the maximum value of 40 in ‘users’ collection

db.users.updateMany({}, { $max: { age: 40 } })

Update the age of users to the minimum value of 20 in ‘users’ collection

db.users.updateMany({}, { $min: { age: 20 } })

Increment the age of users by 1 in ‘users’ collection

db.users.updateMany({}, { $inc: { age: 1 } })

Multiply the age of users by 1.1 in ‘users’ collection

db.users.updateMany({}, { $mul: { age: 1.1 } })

We use the $max and $min operators to update fields to the maximum or minimum value respectively. The $inc operator increments numeric fields by a specified value. The $mul operator multiplies numeric fields by a specified value.

Array Expression Operators

Find documents where ‘tags’ field is an array in ‘posts’ collection

db.posts.find({ tags: { $isArray: true } })

Find documents in ‘posts’ collection where the size of the ‘tags’ array is 3

db.posts.find({ $expr: { $eq: [{ $size: "$tags" }, 3] } })

Find the first element of the ‘tags’ array in each document of ‘posts’ collection

db.posts.aggregate([
{ $project: { firstTag: { $arrayElemAt: ["$tags", 0] } } }
])

Concatenate the ‘tags’ arrays of all documents in ‘posts’ collection

db.posts.aggregate([
{ $group: { _id: null, allTags: { $concatArrays: "$tags" } } }
])

Reverse the ‘tags’ array in all documents of ‘posts’ collection

db.posts.updateMany({}, { $reverseArray: "$tags" })

We use the $isArray operator to find documents where a field is an array. The $size operator is used to find documents based on the size of an array field. With $arrayElemAt, we retrieve a specific element from an array field. The $concatArrays operator concatenates arrays. Finally, $reverseArray reverses the elements of an array.

Array Update Operators

Remove all occurrences of “mongodb” from the ‘tags’ array in ‘posts’ collection

db.posts.updateMany({}, { $pull: { tags: "mongodb" } })

Remove the last element from the ‘tags’ array in all documents of ‘posts’ collection

db.posts.updateMany({}, { $pop: { tags: 1 } })

Remove all occurrences of “nosql” and “database” from the ‘tags’ array in ‘posts’ collection

db.posts.updateMany({}, { $pullAll: { tags: ["nosql", "database"] } })

Add “newtag” to the end of the ‘tags’ array in a specific document in ‘posts’ collection

db.posts.updateOne({ title: "Introduction to MongoDB" }, { $push: { tags: "newtag" } })

Update the ‘tags’ array in all documents where “mongodb” is present with “updatedtag”

db.posts.updateMany({ tags: "mongodb" }, { $set: { "tags.$": "updatedtag" } })

String Expression Operators

Concatenate the ‘title’ and ‘content’ fields into a new field ‘fullText’ in ‘posts’ collection

db.posts.aggregate([
{
$project: {
fullText: { $concat: ["$title", " ", "$content"] }
}
}
])

Compare the ‘title’ field case insensitively to “MongoDB” in ‘posts’ collection

db.posts.find({ $expr: { $eq: [{ $strcasecmp: ["$title", "MongoDB"] }, 0] } })

Convert the ‘title’ field to uppercase in ‘posts’ collection

db.posts.updateMany({}, { $set: { title: { $toUpper: "$title" } } })

Convert the ‘title’ field to lowercase in ‘posts’ collection

db.posts.updateMany({}, { $set: { title: { $toLower: "$title" } } })

Extract the first 5 characters from the ‘title’ field in ‘posts’ collection

db.posts.aggregate([
{ $project: { firstFiveChars: { $substrCP: ["$title", 0, 5] } } }
])

We use the $concat operator to concatenate fields or strings. $strcasecmp compares strings case insensitive. The $toUpper operator converts a string to uppercase. $toLower converts a string to lowercase. $substrCP extracts a substring from a string based on code points.

MongoDB Cheat Sheet

MongoDB is a document-oriented NoSQL database that revolutionizes data storage with its flexibility and scalability. By storing data in JSON-like documents, MongoDB offers developers a powerful and intuitive way to handle complex data structures. From basic CRUD operations to advanced aggregation techniques, MongoDB empowers users to build robust and dynamic applications with ease.

In this MongoDB cheat sheet, we’ll delve into MongoDB’s key concepts, including data types, CRUD operations, query techniques, aggregation framework, indexing strategies, transaction support, and data modeling approaches. Each section is packed with examples and explanations to help you grasp MongoDB’s functionalities quickly and efficiently.

Similar Reads

MongoDB Basics

...

CRUD Operations in MongoDB

This section dives into CRUD operations, the foundation of interacting with your MongoDB database. We’ll explore how to Create, Read, Update, and Delete documents, giving you the power to manage your data effectively. Get ready to add, retrieve, modify, and remove information with ease!...

MongoDB Operators

MongoDB operators are special symbols or keywords that unlock the power of your data. Just like a chef uses tools to prepare a meal, these operators help you find, modify, and analyze information stored in your MongoDB database. Mastering these operators empowers you to efficiently query, manipulate, and unlock the hidden insights within your data....

MongoDB Aggregation Framework

We’ll perform various aggregation operations using MongoDB’s aggregation framework...

MongoDB Indexing

Indexing enhances query performance and allows for efficient data retrieval in MongoDB...

Transactions in MongoDB

MongoDB supports multi-document ACID transactions, allowing for atomicity, consistency, isolation, and durability....

Data Modeling in MongoDB

Data modeling in MongoDB involves designing schemas and relationships between documents....

Conclusion

MongoDB stands out as a versatile and powerful document-oriented NoSQL database, offering developers a flexible and scalable solution for handling complex data structures. Throughout this cheat sheet, we’ve explored MongoDB’s key concepts, from its fundamental data types to advanced features such as CRUD operations, querying techniques, aggregation framework, indexing strategies, transaction support, and data modeling approaches....