db.command.aggregate.abs
1. Operator Description
Function: Returns the absolute value of a numeric parameter.
Declaration: db.command.aggregate.abs(num)
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
- | Expression | Required | aggregate expression (must resolve to a number) |
Notes:
If the expression resolves to
null
or points to a non-existent field,abs
returnsnull
. If the value resolves toNaN
, it returnsNaN
.
3. Sample Code
Suppose the collection ratings
contains the following records:
{ _id: 1, start: 5, end: 8 }
{ _id: 2, start: 4, end: 4 }
{ _id: 3, start: 9, end: 7 }
{ _id: 4, start: 6, end: 7 }
···
The absolute difference between start
and end
for each record can be calculated as follows:
// 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('ratings')
.aggregate()
.project({
delta: $.abs($.subtract(['$start', '$end']))
})
.end()
console.log(res.data)
}
The returned result is as follows:
{ "_id" : 1, "delta" : 3 }
{ "_id" : 2, "delta" : 0 }
{ "_id" : 3, "delta" : 2 }
{ "_id" : 4, "delta" : 1 }