$cmp Operator - (MongoDB Miscellaneous)
MongoDB provides a set of operators that can be used to perform various operations. One such operator is the $cmp
operator, which compares two values and returns -1, 0 or 1 based on whether the first value is less than, equal to, or greater than the second value. In this page, we will discuss the $cmp
operator in MongoDB.
Syntax
{ $cmp: [ <expression1>, <expression2> ] }
Example
Consider a collection named "books" which has the following documents:
{ _id: 1, title: "The Great Gatsby", author: "F. Scott Fitzgerald", price: 10 }
{ _id: 2, title: "To Kill a Mockingbird", author: "Harper Lee", price: 12 }
{ _id: 3, title: "1984", author: "George Orwell", price: 8 }
The following query uses the $cmp
operator to compare the price
value of each book document with the value 10
and returns books which have a price greater than 10.
db.books.find( { $cmp: [ "$price", 10 ] } : { $gt: 0 } )
The output of the above query would be:
{ _id: 2, title: "To Kill a Mockingbird", author: "Harper Lee", price: 12 }
Explanation
The $cmp
operator compares the two expressions specified in the array. If the first expression is less than the second expression, then $cmp
returns -1. If the two expressions are equal then $cmp
returns 0. If the first expression is greater than the second expression, then $cmp
returns 1.
In the example above, we used the $cmp
operator to compare the price
value of book documents to the value 10
. If the price
is greater than 10, then $cmp
will return 1. We then specified the result of $cmp
as the input to the $gt
operator. The $gt
operator returns true if the expression is greater than the specified value (0
in this case), which indicates that the price
value of the book document is greater than 10
.
Use
The $cmp
operator is used to compare two values in MongoDB. It is particularly useful when used in an aggregation pipeline to compare fields in a document and perform a specific operation based on the comparison result.
Important Points
- The
$cmp
operator compares two expressions in MongoDB and returns -1, 0, or 1 based on the comparison result. - It is often used in an aggregation pipeline to compare fields in a document and perform a specific operation based on the comparison result.
Summary
In this page, we discussed the $cmp
operator in MongoDB. We covered the syntax, example, output, explanation, use, and important points of the $cmp
operator. By using the $cmp
operator, you can compare two values in MongoDB and use the comparison result in various operations such as aggregation pipelines.