db.command.aggregate.map
1. Operator Description
Function: Similar to the map
method on JavaScript Array, it transforms each element of a given array according to a specified transformation method to produce a new array.
Declaration: db.command.aggregate.map({ input: expression, as: string, in: expression })
2. Operator Parameters
Field | Type | Required | Description |
---|---|---|---|
input | Expression | Required | An expression that resolves to an array. |
as | string | No | Optional. The variable representing each element in the array, defaults to this. |
in | Expression | Required | An expression that can be applied to each element of a given array. The element name is determined by the as parameter (parameter names must be prefixed with $$ , e.g., $$this ). |
3. Sample Code
Suppose the collection stats
contains the following records:
{
"_id": 1,
"sales": [ 1.32, 6.93, 2.48, 2.82, 5.74 ]
}
{
"_id": 2,
"sales": [ 2.97, 7.13, 1.58, 6.37, 3.69 ]
}
Truncate each number to an integer and then sum them up.
// 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('stats')
.aggregate()
.project({
truncated: $.map({
input: '$sales',
as: 'num',
in: $.trunc('$$num')
})
})
.project({
total: $.sum('$truncated')
})
.end()
console.log(res.data)
}
The returned result is as follows:
{ "_id": 1, "index": 16 }
{ "_id": 2, "index": 19 }