MongoDB $cmp

In MongoDB, the $cmp aggregation pipeline operator compares two values and returns either -1, 1, or 0, depending on whether the first value is less than, greater than, or equal to the first value.

Specifically, the $cmp operator returns:

  • -1 if the first value is less than the second.
  • 1 if the first value is greater than the second.
  • 0 if the two values are equivalent.

Example

Suppose we have a collection called data with the following documents:

{ "_id" : 1, "a" : 2, "b" : 2 }
{ "_id" : 2, "a" : 2, "b" : 3 }
{ "_id" : 3, "a" : 3, "b" : 2 }

We can use the $cmp operator to compare the a and b fields:

db.data.aggregate(
  [
    { $project: { 
        _id: 0,
        a: 1,
        b: 1,
        result: { $cmp: [ "$a", "$b" ] }
      }
    }
  ]
)

Result:

{ "a" : 2, "b" : 2, "result" : 0 }
{ "a" : 2, "b" : 3, "result" : -1 }
{ "a" : 3, "b" : 2, "result" : 1 }

Comparing Different Types

The $cmp operator compares both value and type, using the specified BSON comparison order for values of different types.

Suppose we add the following documents to our collection:

{ "_id" : 4, "a" : ISODate("2021-01-03T23:30:15.100Z"), "b" : ISODate("2019-12-08T04:00:20.112Z") }
{ "_id" : 5, "a" : 2, "b" : ISODate("2019-12-08T04:00:20.112Z") }
{ "_id" : 6, "a" : ISODate("2019-12-08T04:00:20.112Z"), "b" : 2 }
{ "_id" : 7, "a" : null, "b" : 2 }
{ "_id" : 8, "a" : 2, "b" : null }
{ "_id" : 9, "a" : null, "b" : null }
{ "_id" : 10, "a" : Infinity, "b" : 3 }
{ "_id" : 11, "a" : 2, "b" : Infinity }
{ "_id" : 12, "a" : Infinity, "b" : Infinity }

Here’s what happens when we apply $cmp to the new documents:

db.data.aggregate(
  [
    { $match: { _id: { $nin: [ 1, 2, 3 ] } } },
    { $project: { 
        a: 1,
        b: 1,
        result: { $cmp: [ "$a", "$b" ] }
      }
    }
  ]
).pretty()

Result:

{
	"_id" : 4,
	"a" : ISODate("2021-01-03T23:30:15.100Z"),
	"b" : ISODate("2019-12-08T04:00:20.112Z"),
	"result" : 1
}
{
	"_id" : 5,
	"a" : 2,
	"b" : ISODate("2019-12-08T04:00:20.112Z"),
	"result" : -1
}
{
	"_id" : 6,
	"a" : ISODate("2019-12-08T04:00:20.112Z"),
	"b" : 2,
	"result" : 1
}
{ "_id" : 7, "a" : null, "b" : 2, "result" : -1 }
{ "_id" : 8, "a" : 2, "b" : null, "result" : 1 }
{ "_id" : 9, "a" : null, "b" : null, "result" : 0 }
{ "_id" : 10, "a" : Infinity, "b" : 3, "result" : 1 }
{ "_id" : 11, "a" : 2, "b" : Infinity, "result" : -1 }
{ "_id" : 12, "a" : Infinity, "b" : Infinity, "result" : 0 }