$cmp

The `$cmp` operator compares two specified values. The $cmp operator returns -1 if the first value is less than the second, 0 if the two values are equal and 1 if the first value is greater than the second.

Syntax

{ $cmp: [<firstValueToCompare>, <secondValueToCompare>] }

Parameters

firstValueToComparestringrequired

The first value which is compared to the second by the $cmp operator

secondValueToComparestringrequired

The second value being compared to by the $cmp operator

Examples

Compare the total sales of stores to $25,000

To compare the total sales of stores to $25,000, first run a query to filter stores. Then, use $cmp to compare the sales.totalSales field to 25000.

Query:

db.stores.aggregate([{
    $match: { company: { $in: ["Boulder Innovations"] } }
}, {
    $project: {
        name: 1,
        "sales.salesByCategory.totalSales": 1,
        greaterThan25000: { $cmp: ["$sales.revenue", 25000] }
    }
}])

Output:

[
    { "_id": "a5040801-d127-4950-a320-e55f6aed4b36", "name": "Boulder Innovations | DJ Equipment Pantry - West Christopher", "sales": { "salesByCategory": [{ "totalSales": 21522 }] }, "greaterThan25000": -1 },
    { "_id": "bb6e097a-e204-4b64-9f13-5ae8426fcc76", "name": "Boulder Innovations | Kitchen Appliance Outlet - Lake Chazville", "sales": { "salesByCategory": [{ "totalSales": 24062 }, { "totalSales": 24815 }] }, "greaterThan25000": 1 }
]

Related