AggregateCommand.map(value: any): Object

View Markdown

Last edited on 2026-07-04

Supported on: Mini Program 2.7.4, Cloud Functions 0.8.1, Web

Aggregation operator. Similar to the map method on JavaScript Arrays, it transforms each element of a given array using a specified transformation function to generate a new array.

Parameters

value: any

Return Value

Object

API Description

The syntax is as follows:

db.command.aggregate.map({
  input: <expression>,
  as: <string>,
  in: <expression>
})
Field Description
input An expression that can be resolved into an array
as Optional. A variable used to represent each element in the array. Defaults to this
in An expression applied to each element in the specified array. The name of each element is determined by the as parameter (the parameter name must be prefixed with $$, e.g., $$this)

Sample Code

Assume 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 calculate the sum

const $ = db.command.aggregate
db.collection('stats').aggregate()
  .project({
    truncated: $.map({
      input: '$sales',
      as: 'num',
      in: $.trunc('$$num'),
    })
  })
  .project({
    total: $.sum('$truncated')
  })
  .end()

The returned results are as follows:

{ "_id": 1, "index": 16 }
{ "_id": 2, "index": 19 }