MongoDB Aggregation
MongoDB $cmp Operator
Photo Credit to CodeToFun
🙋 Introduction
In MongoDB's aggregation framework, the $cmp
operator emerges as a powerful tool for comparing numerical values within documents. This operator enables users to determine the relative order of two values, facilitating sorting, filtering, and other operations based on comparison criteria.
Let's delve into the details of how the $cmp
operator functions within MongoDB's aggregation pipelines.
💡 Syntax
The syntax for the $cmp
method is straightforward:
{ $cmp: [ <expression1>, <expression2> ] }
- $cmp: This operator signifies that the subsequent operation will perform a comparison.
- <expression1> and <expression2>: These represent the expressions whose values will be compared. They could be field references, mathematical expressions, or values.
📝 Example
⌨️ Input
Consider a collection named students containing documents with fields name and score, representing student information. Here are sample documents from the students collection:
[
{ "_id": ObjectId("609c26812e9274a86871bc6a"), "name": "Alice", "score": 85 },
{ "_id": ObjectId("609c26812e9274a86871bc6b"), "name": "Bob", "score": 75 },
{ "_id": ObjectId("609c26812e9274a86871bc6c"), "name": "Charlie", "score": 90 }
]
🔄 Aggregation
Suppose we want to compare the scores of students and assign them labels based on their performance (e.g., "High", "Medium", "Low"). Here's how you can achieve this using the $cmp
operator:
db.students.aggregate([
{
$project: {
name: 1,
score: 1,
performance: {
$switch: {
branches: [
{ case: { $eq: [{ $cmp: ["$score", 80] }, 1] }, then: "High" },
{ case: { $eq: [{ $cmp: ["$score", 60] }, 1] }, then: "Medium" }
],
default: "Low"
}
}
}
}
])
🧩 Explanation
- $project: This stage reshapes documents to include additional fields based on the specified expressions.
- $cmp: Compares the score field with reference values (80 and 60 in this case) to determine the relative order.
- $switch: Evaluates conditions and returns corresponding results based on the comparison outcomes.
When discussing how the above aggregation works:
- For the document with name "Alice" and score 85, the score is greater than or equal to 80, so the performance is labeled as "High".
- For the document with name "Bob" and score 75, the score is less than 80 but greater than or equal to 60, so the performance is labeled as "Medium".
- For the document with name "Charlie" and score 90, the score is greater than or equal to 80, so the performance is labeled as "High".
💻 Output
Now, let's take a look at the output generated by the aggregation pipeline:
[
{ "_id": ObjectId("609c26812e9274a86871bc6a"), "name": "Alice", "score": 85, "performance": "High" },
{ "_id": ObjectId("609c26812e9274a86871bc6b"), "name": "Bob", "score": 75, "performance": "Medium" },
{ "_id": ObjectId("609c26812e9274a86871bc6c"), "name": "Charlie", "score": 90, "performance": "High" }
]
📚 Use Cases
Sorting:
The
$cmp
operator is useful for sorting documents based on numerical values, allowing users to define custom sorting orders.Categorization:
By comparing values against thresholds, the
$cmp
operator facilitates the categorization of data into meaningful groups or labels.Ranking:
Users can use the
$cmp
operator to rank documents based on numerical attributes, such as scores or ratings.
🎉 Conclusion
The $cmp
operator in MongoDB's aggregation framework provides a flexible and efficient means of comparing numerical values within documents, enabling users to derive meaningful insights and make informed decisions based on comparison criteria. Whether you're sorting, categorizing, or ranking data, mastering the usage of $cmp
empowers you to efficiently manipulate numerical data within MongoDB aggregation pipelines.
With its intuitive syntax and diverse applications, the $cmp
operator proves to be a valuable asset for handling numerical data effectively within MongoDB. Incorporate it into your aggregation pipelines to unlock new dimensions of data analysis and gain deeper insights into your datasets.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (MongoDB $cmp Operator), please comment here. I will help you immediately.