SDK数据库 Aggregate记录分组


当前第2页 返回上一页

累计器必须是以下操作符之一:

  • addToSet
  • avg
  • first
  • last
  • max
  • min
  • push
  • stdDevPop
  • stdDevSamp
  • sum

内存限制

该阶段有 100M 内存使用限制。

示例 1:按字段值分组

假设集合 avatar 有如下记录:

{
  _id: "1",
  alias: "john",
  region: "asia",
  scores: [40, 20, 80],
  coins: 100
}
{
  _id: "2",
  alias: "arthur",
  region: "europe",
  scores: [60, 90],
  coins: 20
}
{
  _id: "3",
  alias: "george",
  region: "europe",
  scores: [50, 70, 90],
  coins: 50
}
{
  _id: "4",
  alias: "john",
  region: "asia",
  scores: [30, 60, 100, 90],
  coins: 40
}
{
  _id: "5",
  alias: "george",
  region: "europe",
  scores: [20],
  coins: 60
}
{
  _id: "6",
  alias: "john",
  region: "asia",
  scores: [40, 80, 70],
  coins: 120
}
const $ = db.command.aggregate
db.collection('avatar').aggregate()
  .group({
    _id: '$alias',
    num: $.sum(1)
  })
  .end()

返回结果如下:

{
  "_id": "john",
  "num": 3
}
{
  "_id": "authur",
  "num": 1
}
{
  "_id": "george",
  "num": 2
}

示例 2:按多个值分组

可以给 _id 传入记录的方式按多个值分组。还是沿用上面的示例数据,按各个区域(region)获得相同最高分(score)的来分组,并求出各组虚拟币(coins)的总量:

const $ = db.command.aggregate
db.collection('avatar').aggregate()
  .group({
    _id: {
      region: '$region',
      maxScore: $.max('$scores')
    },
    totalCoins: $.sum('$coins')
  })
  .end()

返回结果如下:

{
  "_id": {
    "region": "asia",
    "maxScore": 80
  },
  "totalCoins": 220
}
{
  "_id": {
    "region": "asia",
    "maxScore": 100
  },
  "totalCoins": 100
}
{
  "_id": {
    "region": "europe",
    "maxScore": 90
  },
  "totalCoins": 70
}
{
  "_id": {
    "region": "europe",
    "maxScore": 20
  },
  "totalCoins": 60
}



标签:微信小程序

返回前面的内容

相关阅读 >>

微信小程序api 绘图setstrokestyle(设置线条样式)

微信小程序api wifi

微信小程序云开发服务端数据库api 获取数据库的引用

微信小程序 纯数据字段

微信小程序云开发sdk文档 常量

微信小程序 小程序宿主环境

微信小程序云开发服务端数据库api 查询筛选条件

微信小程序云开发api 替换更新一条记录

微信小程序 小程序使用batchgetorder

sdk数据库 aggregate记录分组

更多相关阅读请进入《微信小程序》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...