Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

SDK database Collection aggregation operation


May 20, 2021 WeChat Mini Program Development Document


Table of contents


Collection.aggregate(): Aggregate

Support: Small program 2.7.4, cloud function 0.8.1, Web

To initiate an aggregation operation, you need to call the end method flag to end the definition and actually initiate the aggregation operation after defining the aggregation pipeline stage

Returns a value

Aggregate

The sample code

const $ = db.command.aggregate
db.collection('books').aggregate()
  .group({
    // 按 category 字段分组
    _id: '$category',
    // 让输出的每组记录有一个 avgSales 字段,其值是组内所有记录的 sales 字段的平均值
    avgSales: $.avg('$sales')
  })
  .end()
  .then(res => console.log(res))
  .catch(err => console.error(err))

The small terminal is compatible with callback styles

const $ = db.command.aggregate
db.collection('books').aggregate()
  .group({
    // 按 category 字段分组
    _id: '$category',
    // 让输出的每组记录有一个 avgSales 字段,其值是组内所有记录的 sales 字段的平均值
    avgSales: $.avg('$sales')
  })
  .end({
    success: function(res) {
      console.log(res)
    },
    fail: function(err) {
      console.error(err)
    }
  })