MongoDB $cmp Operator
The MongoDB $cmp operator compares two values or types and returns a result based on the comparison. It returns 1 if the first value is greater than the second, -1 if the first value is less than the second, and 0 if both values are equal.
$cmp Operator in MongoDB
$cmp operator in MongoDB is one of the comparison expression operators. It is used in the aggregation pipeline stages.
The $cmp operator compares both value and type, using the specified BSON comparison order for values of different types.
Syntax
{ $cmp: [ <expression1>, <expression2> ] }
MongoDB $cmp Operator Examples
Let’s look at some examples of the $cmp operator in MongoDB to understand the operator.
In the following examples, we are working with:
Database: w3wiki
Collection: example
Document: two documents that contain the details of the shapes in the form of field-value pairs.
Using $cmp Operator example:
In this example, we are comparing the value of the side field with 4 and $cmp operator return 0 which means both values are equal.
Query:
db.example.aggregate([{$match: {name: "Square"}},
... {$project: {result: {$cmp:["$side", 4]}}}])
Output:
Using $cmp Operator in the Embedded Document:
In this example, we are comparing the value of the measurement.height field with the value of the measurement.width field and $cmp operator return -1 which means both values of measurement.height field is less than the value of the measurement.width field.
Query:
db.example.aggregate([{$match: {name: "Rectangle"}},
... {$project: {result:
... {$cmp:["$measurement.height", "$measurement.width"]}}}])
Output:
Important Points About MongoDB $cmp Operator
- The $cmp operator is used to compare two values or types and returns the result. It returns -1 if the first value is less than the second, 1 if the first value is greater than the second, and 0 if both values are equal.
- The $cmp operator compares both value and type, using the specified BSON comparison order for values of different types.
- The $cmp operator is used in the aggregation pipeline stages.
Contact Us