MongoDB $cmp Operator

What is the $cmp operator in MongoDB?

MongoDB provides a variety of aggregation pipeline operators. The $cmp operator is one of those operators. The $cmp operator is used to compare two values or types and returns the result.

It returns the following result according to these conditions:

  • If both values are equal, it returns 0.
  • If the first value is greater than the second value, it returns 1.
  • If the first value is less than the second value, it returns -1.

Syntax of the $log10 operator:

Examples:

Suppose we have a collection of the products with the following documents.

Example 1: Using $cmp Operator

In this example, we're going to compare the length and width fields using the $cmp operator.

Output:

{
         "_id" : 1, 
         "name" : "rectangle",
         "length" : 11,
         "breath" : 10,
         "result" : 1
}
{
         "_id" : 2, 
         "name" : "square",
         "length" : 10,
         "breath" : 10,
         "result" : 0
}
{
         "_id" : 3, 
         "name" : "rectangle",
         "length" : 14,
         "breath" : 16,
         "result" : -1
}
{
         "_id" : 4, 
         "name" : "square",
         "length" : 6,
         "breath" : 6,
         "result" : 0
}
{
         "_id" : 5, 
         "name" : "rectangle",
         "length" : 11,
         "breath" : 16,
         "result" : -1
}   

Suppose we add the following documents to our collection:

Example 2: Comparing null values

Output:

{
         "_id" : 6, 
         "name" : "rectangle",
         "length" : null,
         "breath" : 10,
         "result" : -1
}
{
         "_id" : 7, 
         "name" : "square",
         "length" : 10,
         "breath" : null,
         "result" : 1
}
{
         "_id" : 8, 
         "name" : "rectangle",
         "length" : null,
         "breath" : null,
         "result" : 0
}    

Suppose we add the following documents to our collection:

Example 3: Comparing different types

Output:

{
         "_id" : 9, 
         "name" : "item_1",
         "a" : ISODate("2020-05-09T23:30:15.100Z"),
         "b" : 10,
         "result" : 1
}
{
         "_id" : 10, 
         "name" : "item_2",
         "a" : 10,
         "b" : ISODate("2012-11-18T04:00:20.112Z"),	
         "result" : -1
}
{
         "_id" : 11, 
         "name" : "item_3",
         "a" : ISODate("2018-11-14T04:00:20.112Z"),
         "b" : ISODate("2015-10-07T04:00:20.112Z"),
         "result" : 1
}   





Latest Courses