db.command.aggregate.cmp
1. Operator Description
Function: Given two values, returns their comparison result.
Declaration: db.command.aggregate.cmp([expression1, expression2])
- If the first value is less than the second value, return -1
- If the first value is greater than the second value, return 1
- If the two values are equal, return 0
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | <Array>Expression | Required | An array containing two aggregation expressions |
3. Sample Code
Suppose the collection price
contains the following records:
{ "_id": 1, "shop1": 10, "shop2": 100 }
{ "_id": 2, "shop1": 80, "shop2": 20 }
{ "_id": 3, "shop1": 50, "shop2": 50 }
Compare the prices of all items between shop1
and shop2
.
// Sample code in the Cloud Function environment
const tcb = require('@cloudbase/node-sdk');
const app = tcb.init({
env:'xxx'
})
const db = app.database();
const $ = db.command.aggregate
exports.main = async (event, context) => {
const res = await db.collection('price').aggregate()
.project({
compare: $.cmp(['$shop1', '$shop2']))
})
.end()
console.log(res.data)
}
The returned result is as follows:
{ "_id": 1, "compare": -1 }
{ "_id": 2, "compare": 1 }
{ "_id": 3, "compare": 0 }