mongo 聚合统计查询之$bucket

mongo聚合查询之 $bucket的作用:

大致说明:分段统计表的数据

$bucket用法支持mongo3.4及以上的版本

语法:先看字面意思做个大致了解

{
  $bucket: {
      groupBy: <expression>, // 需要统计的信息 可以是表达式或者字段
      boundaries: [ <lowerbound1>, <lowerbound2>, ... ], // 约束信息的范围
      default: <literal>, // 不在约束范围内的默认值
      output: { //输出的字段信息
         <output1>: { <$accumulator expression> },
         ...
         <outputN>: { <$accumulator expression> }
      }
   }
}

准备数据:

{ "_id" : 1, "title" : "title1", "year" : 1926,
    "price" : NumberDecimal("199.99") }
{ "_id" : 2, "title" : "title2", "year" : 1902,
    "price" : NumberDecimal("280.00") }
{ "_id" : 3, "title" : "title3", "year" : 1925,
    "price" : NumberDecimal("76.04") }
{ "_id" : 4, "title" : "title4",
    "price" : NumberDecimal("167.30") }
{ "_id" : 5, "title" : "title5
    "price" : NumberDecimal("483.00") }
{ "_id" : 6, "title" : "title6" : 1913,
    "price" : NumberDecimal("385.00") }
{ "_id" : 7, "title" : "title7", "year" : 1893}
{ "_id" : 8, "title" : "title8", "year" : 1918,
    "price" : NumberDecimal("118.42") }

执行查询:

db.artwork.aggregate( [
  {
    $bucket: {
      groupBy: "$price", // 对prices字段进行统计查询
      boundaries: [ 0, 200, 400 ], // 数据的边界范围,包左不包右
      default: "Other", // 不在boundaries内的默认名称
      output: {
        "count": { $sum: 1 }, // 统计
        "titles" : { $push: "$title" } // 将改范围内的title组成数组
      }
    }
  }
] )


结果:

{
  "_id" : 0,
  "count" : 4,
  "titles" : ["title1","title3","title4","title8"]
}// 0<=prices<200
{
  "_id" : 200,
  "count" : 2,
  "titles" : [
    "title2",
    "title6"
  ]
}// 200<=prices<400
{
  "_id" : "Other",
  "count" : 2,
  "titles" : [
    "title5",
    "title7"
  ]
}// 不在0-400范围内的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值