MongoDB聚合,按值区间分组,

2024-04-24

MongoDB 文档:

[{
  _id: '123213',
  elevation: 2300,
  area: 25
},
{
  _id: '343221',
  elevation: 1600,
  area: 35,
},
{
  _id: '545322',
  elevation: 500
  area: 12,
},
{
  _id: '234234',
  elevation: null,
  area: 5
}]

我想按照给定的海拔间隔对它们进行分组并总结面积属性。

  • 第 1 组:
  • 第 2 组:0 - 1500
  • 第 3 组:1501 - 3000,
  • 第 4 组:> 3000

所以预期的输出是:

[{
   interval: '1501-3000',
   count: 2,
   summarizedArea: 60 
},
{
   interval: '0-1500',
   count: 1,
   summarizedArea: 12,
},
{
   interval: 'N/A',
   count: 1,
   summarizedArea: 5
}]

如果可能的话,我想使用aggregation pipeline.

也许与$range?或者组合$gte and $lte?


正如菲利克斯建议的那样$bucket https://docs.mongodb.com/manual/reference/operator/aggregation/bucket/应该可以完成这项工作,但界限应该略有不同,以便更好地处理负面和负面影响N/A values:

db.collection.aggregate([
  {
    $bucket: {
      groupBy: "$elevation",
      boundaries: [ -Number.MAX_VALUE, 0, 1501, 3001, Number.POSITIVE_INFINITY ],
      default: Number.NEGATIVE_INFINITY,
      output: {
        "count": { $sum: 1 },
        "summarizedArea" : { $sum: "$area" }
      }
    }
  }
])

可以将下面的格式化阶段添加到管道中以调整响应的形状:

  { $group: {
      _id: null,
      documents: { $push: {          
          interval: { $let: {
              vars: {
                  idx: { $switch: {
                      branches: [
                          { case: { $eq: [ "$_id", -Number.MAX_VALUE ] }, then: 3 },
                          { case: { $eq: [ "$_id", 0 ] }, then: 2 },
                          { case: { $eq: [ "$_id", 1501 ] }, then: 1 },
                          { case: { $eq: [ "$_id", 3001 ] }, then: 0 }
                      ],
                      default: 4
                  } }
              },
              in: { $arrayElemAt: [ [ ">3000", "1501-3000", "0-1500", "<0", "N/A" ], "$$idx" ] } 
          } },
          count: "$count",
          summarizedArea: "$summarizedArea"
      } }
  } }

$group https://docs.mongodb.com/manual/reference/operator/aggregation/group/ with _id: null $push https://docs.mongodb.com/manual/reference/operator/aggregation/push/将所有组放入单个文档的数组中。

$let https://docs.mongodb.com/manual/reference/operator/aggregation/let/ maps $_id从上一阶段到数组中定义的间隔的文本标签[ ">3000", "1501-3000", "0-1500", "<0", "N/A" ]。为此,它计算idx标签的索引使用$switch https://docs.mongodb.com/manual/reference/operator/aggregation/switch/.

在应用程序级别实现逻辑一定要简单得多,除非您绝对需要在管道中执行它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MongoDB聚合,按值区间分组, 的相关文章

随机推荐