MongoDB $cmp Operator (original) (raw)

Last Updated : 5 May, 2026

The MongoDB $cmp operator compares two values and returns their order. It is used in aggregation pipelines for sorting and conditional logic, and follows BSON type ordering for different data types.

Syntax

{ $cmp: [ , ] }

Features of the MongoDB $cmp Operator

Here are some features discussed:

MongoDB $cmp Operator Examples

Examples of the $cmp operator in MongoDB. In the following examples, we are working with:

Screenshot-2026-02-09-104701

Example 1: Using $cmp to Compare a Field with a Static Value

The $cmp operator compares the value of the side field with 4 and returns 0, which indicates that both values are equal.

**Query:

db.example.aggregate([{$match: {name: "Square"}}, {$project: {result: {$cmp:["$side", 4]}}}])

**Output:

Screenshot-2026-02-09-104909

Example 2: Using $cmp Operator in the embedded Document

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:

cmp