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:
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.
Contact Us