需要使用到云开发数据库方法提供的聚合操作符累计器操作符,详见参考文档

示例代码

假设集合 goods 的数据如下:

{ "type": "水果", "name": "苹果", "price": 84 }
{ "type": "水果", "name": "橘子", "price": 96 }
{ "type": "蔬菜", "name": "青菜", "price": 80 }
{ "type": "蔬菜", "name": "茄子", "price": 100 }

借助 push 操作,对不同分组( group )的所有记录,聚合所有数据并且将其放入一个新的字段中,进一步结构化和语义化数据。

db
  .collection('goods')
  .aggregate()
  .group({
    _id: '$type',
    list: db.command.aggregate.push({
      name: '$name',
      price: '$price'  
    })
  })
  .end()

输出结果如下:

{
  "_id": "水果",
  "students": [{
    "name": "苹果",
    "price": 84
    }, {
    "name": "橘子",
    "price": 96
  }]
} {
  "_id": "蔬菜",
  "students": [{
    "name": "青菜",
    "price": 80
    }, {
    "name": "茄子",
    "price": 100
  }]
}

注意的是,聚合阶段_id是必须的,输出的数据如果想修改_id的名称(即修改key的名称,不是修改key所对应value),可使用下面的方法,仅供参考:

let newData = [];
let obj = {};
this.data.map(item => {
  obj = item;
  obj['name'] = item['_id'];  
  delete obj['_id'];
  newData.push(obj)
})

参考文档[1]:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/database/aggregate/Aggregate.group.html
参考文档[2]: https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-sdk-api/database/command/aggregate/AggregateCommand.push.html