Ever feel like you're just scratching the surface of your MongoDB data? Operators are the key to unlocking its full potential! They're like the secret ingredients that turn basic queries into powerful data insights. Whether you need to filter, update, or analyze your data, MongoDB query operators are your go-to toolkit.
In this blog, we'll dive into the world of MongoDB query operators, breaking down each category with clear explanations and real-world examples. Let's get started!
MongoDB operators are classified into various categories based on their functionalities:
Let’s explore each category with its operators, descriptions, and practical examples.
Comparison operators filter documents by comparing field values against specified values.
Operator | Description |
|---|---|
| $eq | Matches documents where the field value is equal to a specified value. |
| $ne | Matches documents where the field value is not equal to a specified value. |
| $gt | Matches documents where the field value is greater than the specified value. |
| $gte | Matches documents where the field value is greater than or equal to the specified value. |
| $lt | Matches documents where the field value is less than the specified value. |
| $lte | Matches documents where the field value is less than or equal to the specified value. |
| $in | Matches documents where the field value is present in the specified array. |
| $nin | Matches documents where the field value is not present in the specified array. |
$eq (Equal)
Suppose we have a collection of books, and we need to find all the books that have a price exactly equal to 1000
db.products.find({ "price": { "$eq": 1000 } })Imagine we want to find all products that are not in the "Electronics" category. This query filters out any product with the category "Electronics".
db.products.find({ "category": { "$ne": "Electronics" } })If we're looking for products with a price higher than 1000, this query will return those documents.
db.products.find({ "price": { "$gt": 1000 } })This query finds products with a price of 500 or more.
db.products.find({ "price": { "$gte": 500 } })$lt (Less Than)
To find products with stock levels below 10, this query is used.
db.products.find({ "stock": { "$lt": 10 } })This query finds products with a rating of 4 or less.
db.products.find({ "rating": { "$lte": 4 } })Suppose we want to find all products that belong to either the "Electronics" or "Clothing" categories.
db.products.find({ "category": { "$in": ["Electronics", "Clothing"] } })This query finds products that are not in the "Furniture" or "Toys" categories.
db.products.find({ "category": { "$nin": ["Furniture", "Toys"] } })Key Points:
Logical operators let you combine multiple conditions to create more complex queries.
Operator | Description |
| $and | Joins multiple query conditions and returns documents that match all conditions. |
| $or | Joins multiple query conditions and returns documents that match at least one condition. |
| $nor | Returns documents that do not match any of the given conditions. |
| $not | Inverts the effect of another operator. |
If we need to find all products that are in the "Electronics" category and have a price greater than 1000.
db.products.find({ "$and": [ { "category": "Electronics" }, { "price": { "$gt": 1000 } } ] })This query finds products that are either in the "Clothing" category or have a stock level greater than 100.
db.products.find({ "$or": [ { "category": "Clothing" }, { "stock": { "$gt": 100 } } ] })We want to find products that are neither in the "Electronics" category nor have a price above 2000.
db.products.find({ "$nor": [ { "category": "Electronics" }, { "price": { "$gt": 2000 } } ] })This query finds all products that are not in the "Clothing" category.
db.products.find({ "category": { "$not": { "$eq": "Clothing" } } })Element operators check if a field exists or if it's of a specific data type.
Operator | Description |
| $exists | Matches documents where the field exists or does not exist. |
| $type | Matches documents where the field is of a specific data type. |
This query finds all products where the "discount" field exists, indicating that a discount is applied.
db.products.find({ "discount": { "$exists": true } })Suppose we want to find all products where the "stock" field is stored as an integer, ensuring consistency in our stock data.
db.products.find({ "stock": { "$type": "int" } })Key Points:
Array operators let you query fields that are arrays.
Operator | Description |
| $all | Matches arrays that contain all specified elements. |
| $size | Matches arrays with a specified number of elements. |
| $elemMatch | Matches documents where at least one array element satisfies multiple conditions. |
Find products that have both "Wireless" and "Bluetooth" in the features array:
db.products.find({ "features": { "$all": ["Wireless", "Bluetooth"] } })Suppose you want to find all products that have exactly three tags associated with them.
db.products.find({ "tags": { "$size": 3 } })If we have a collection of products with reviews. You want to find all products where at least one review has a rating greater than 4 and is from a verified buyer.
db.products.find({ "reviews": { "$elemMatch": { "rating": { "$gt": 4 }, "verified": true } } })Key Points:
Evaluation operators provide additional query functionality like regex matching, text searching, and more.
Operator | Description |
| $regex | Matches strings based on a regular expression. |
| $text | Performs text search on indexed fields. |
| $jsonSchema | Validates documents based on a defined JSON schema. |
| $mod | Matches documents where the field value, when divided by a number, gives a specified remainder. |
| $where | Matches documents that satisfy a JavaScript expression. |
Imagine you want to ensure that all product documents have a "price" field that is a number and a "category" field that is a string. This query uses a JSON schema to validate the structure and data types of the documents.
db.products.find({ "$jsonSchema": { "bsonType": "object", "required": ["price", "category"], "properties": { "price": { "bsonType": "number" }, "category": { "bsonType": "string" } } } })If we want to find all products where the price is exactly divisible by 500 (i.e., the remainder is 0).
db.products.find({ "price": { "$mod": [500, 0] } })If we want to find all products where the name contains the word "shirt", regardless of case.This query uses a regular expression to perform a case-insensitive search for "shirt" within the "name" field.
db.products.find({ "name": { "$regex": "shirt", "$options": "i" } })If you have a collection of products with a text index, and you want to find all products that contain the word "gaming", this can be used.
db.products.find({ "$text": { "$search": "gaming" } })If you want to find all products where the stock level is greater than one-tenth of the price, you can use a JavaScript expression in the $where operator to perform this calculation.
db.products.find({ "$where": "this.stock > this.price / 10" })Key Points:
Bitwise operators allow performing bitwise comparisons on integer fields. They're useful when you need to work with data at the bit level.
Operator | Description |
| $bitsAllSet | Matches documents where all specified bit positions are set (1). |
| $bitsAnySet | Matches documents where at least one of the specified bit positions is set (1). |
| $bitsAllClear | Matches documents where all specified bit positions are clear (0). |
| $bitsAnyClear | Matches documents where at least one of the specified bit positions is clear (0). |
Imagine your "stock" field stores integer values representing bit flags. This query finds all products where both the 2nd bit (position 1) and the 3rd bit (position 2) are set to 1.
db.products.find({ "stock": { "$bitsAllSet": [1, 2] } })This query finds all products where either the 2nd bit (position 1) or the 3rd bit (position 2) or both are set to 1 in the "stock" field.
db.products.find({ "stock": { "$bitsAnySet": [1, 2] } })This query finds all products where both the 2nd bit (position 1) and the 3rd bit (position 2) are set to 0 in the "stock" field.
db.products.find({ "stock": { "$bitsAllClear": [1, 2] } })This query finds all products where either the 2nd bit (position 1) or the 3rd bit (position 2) or both are set to 0 in the "stock" field.
db.products.find({ "stock": { "$bitsAnyClear": [1, 2] } })Key Points:
Projection operators allow you to control which fields are included or excluded in your query results, making your data more manageable.
Operator | Description |
| $ | Projects the first matching element from an array. |
| $elemMatch | Projects only the array elements that match the query. |
| $meta | Retrieves metadata like text search scores. |
| $slice | Limits the number of elements in an array. |
Suppose you want to find products that have at least one review with a rating of 5, and you only want to retrieve that first matching review.
db.products.find({ "reviews.rating": 5 }, { "reviews.$": 1 })If you want to retrieve the product name and only those reviews where the rating is greater than 4, this query is perfect.
db.products.find({}, { "name": 1, "reviews": { "$elemMatch": { "rating": { "$gt": 4 } } } })Find products using a text search and return relevance scores.
db.products.find({ "$text": { "$search": "gadget" } }, { "name": 1, "score": { "$meta": "textScore" } })If you only want to see the first two reviews for each product, regardless of the total number of reviews, this query uses $slice to limit the "reviews" array to the first two elements
db.products.find({}, { "name": 1, "reviews": { "$slice": 2 } })Key Points:
Geospatial operators are essential for querying location-based data stored in GeoJSON format. These operators rely on 2dsphere indexes to perform efficient geospatial queries.
Operator | Description |
| $geoWithin | Matches documents within a specified geometry. |
| $geoIntersects | Matches documents where geometries intersect with a given shape. |
| $near | Finds documents nearest to a point. |
| $nearSphere | Finds documents nearest to a point, considering spherical geometry. |
Imagine you have a database of places, and you want to find all the restaurants located within a specific district of a city, defined by a polygon.
db.places.find({ location: { $geoWithin: { $geometry: { type: "Polygon", coordinates: [[[77.58, 12.96], [77.60, 12.96], [77.60, 13.00], [77.58, 13.00], [77.58, 12.96]]] } } } })Suppose you want to find all places that intersect with a particular street, represented as a line string. This query will return all places that touch or cross that street.
db.places.find({ location: { $geoIntersects: { $geometry: { type: "LineString", coordinates: [[77.58, 12.96], [77.60, 13.00]] } } } })If you want to find the closest restaurants to your current location (a specific point) within a 5-kilometer radius, this query will return the places within a given radius.
db.places.find({ location: { $near: { $geometry: { type: "Point", coordinates: [77.595, 12.97] }, $maxDistance: 5000 } } })For finding the closest airports to a city, where distances are significant, using $nearSphere provides more accurate results by accounting for the Earth's curvature.
db.places.find({ location: { $nearSphere: { $geometry: { type: "Point", coordinates: [77.595, 12.97] }, $maxDistance: 5000 } } })Key Points:
Update operators are crucial for modifying existing documents in your MongoDB collection. They allow you to add, change, or remove fields, as well as manipulate array elements.
Operator | Description |
| $set | Updates or adds a field. |
| $inc | Increments or decrements a numeric value. |
| $unset | Removes a field. |
| $rename | Renames a field. |
| $push | Adds an element to an array. |
| $pop | Removes the first or last element from an array. |
$set (Update or Add a Field)
If we need to update the stock count of a specific product. This query finds the product with _id: 1 and sets its "stock" field to 60.
db.products.updateOne({ _id: 1 }, { "$set": { "stock": 60 } })Suppose you want to increase the price of a product by 500. This query finds the product with _id: 2 and adds 500 to its "price" field.
db.products.updateOne({ _id: 2 }, { "$inc": { "price": 500 } })If you need to remove the "discount" field from a product, this query finds the product with _id: 3 and deletes the "discount" field.
db.products.updateOne({ _id: 3 }, { "$unset": { "discount": "" } })If you want to change the field name "category" to "productCategory" for a specific product, this query finds the product with _id: 4 and renames the field.
db.products.updateOne({ _id: 4 }, { "$rename": { "category": "productCategory" } })Add "newArrival" to the tags array for the product with _id: 5.
db.products.updateOne({ _id: 5 }, { "$push": { "tags": "newArrival" } })Remove the first element from the tags array of the product with _id: 1.
db.products.updateOne({ _id: 1 }, { "$pop": { "tags": -1 } })Key Points:
Aggregation operators are powerful tools for transforming and analyzing data in MongoDB. They allow you to perform calculations, group documents, filter, and sort data in a pipeline.
Operator | Description |
| $sum | Computes the sum of values. |
| $avg | Computes the average of values. |
| $min | Returns the minimum value. |
| $max | Returns the maximum value. |
| $group | Groups documents by a specific field. |
| $match | Filters documents. |
| $sort | Sorts documents. |
$sum (Compute Sum of Values)
To find the total stock of all products in our collection.
db.products.aggregate([{ "$group": { "_id": null, "totalStock": { "$sum": "$stock" } } }])To find the average price of all products, this query groups all documents into one and calculates the average of the "price" field.
db.products.aggregate([{ "$group": { "_id": null, "averagePrice": { "$avg": "$price" } } }])Get the product with the lowest price.
db.products.aggregate([{ "$group": { "_id": null, "minPrice": { "$min": "$price" } } }])Get the product with the highest price.
db.products.aggregate([{ "$group": { "_id": null, "maxPrice": { "$max": "$price" } } }])Suppose you want to count the number of products in each category. This query groups the documents by the "category" field and uses $sum to count the number of documents in each group.
db.products.aggregate([{ "$group": { "_id": "$category", "count": { "$sum": 1 } } }])Find the matching products in the "Electronics" category.
db.products.aggregate([{ "$match": { "category": "Electronics" } }])If you want to sort products by price in descending order, this query can be used.
| db.products.aggregate([{ "$sort": { "price": -1 } }]) |
Key Points:
Miru IT Park, Vallankumaranvillai,
Nagercoil, Tamilnadu - 629 002.
Unit 303, Vanguard Rise,
5th Main, Konena Agrahara,
Old Airport Road, Bangalore - 560 017.
Call: +91 6383016411
Email: sales@mafiree.com