Skip to main content

$cmp

The $cmp operator compares two values and returns an integer indicating their relative order: -1 if the first is less than the second, 0 if they are equal, or 1 if the first is greater than the second.

Input

  • An array containing exactly two values to compare

Output

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

Examples

First Value Less Than Second

{
  "$cmp": [
    3,
    5
  ]
}
Result: -1

Equal Values

{
  "$cmp": [
    "hello",
    "hello"
  ]
}
Result: 0

First Value Greater Than Second

{
  "$cmp": [
    {
      "$input": "score"
    },
    85
  ]
}
Result: 1 if the score field is greater than 85, -1 if it’s less than 85, or 0 if it equals 85

String Comparison

{
  "$cmp": [
    "apple",
    "banana"
  ]
}
Result: -1 (lexicographic comparison)