【问题标题】:mongodb aggregation framework - generate _id from functionmongodb聚合框架 - 从函数生成_id
【发布时间】:2013-11-14 01:16:18
【问题描述】:

是否可以在 $group 的 _id 字段中有自定义函数?尽管文档似乎表明可以计算该字段,但我无法使其工作。

例如,假设我有一组文档,其数字字段范围为 1 到 100。我想将数字分类到几个桶中,例如1-20、21-40 等。然后,我将使用此存储桶标识符对不同的字段进行求和/平均。所以我正在尝试这样做:

$group : { _id : bucket("$numberfield") , sum: { $sum: "$otherfield" } }

...其中 bucket 是一个返回字符串的函数,例如“1-20”。

那没用。

http://docs.mongodb.org/manual/reference/operator/aggregation/group/#pipe._S_group

对于这个 _id 字段,您可以指定各种表达式,包括管道中文档的单个字段、上一阶段的计算值、包含多个字段的文档以及其他有效表达式,例如作为常量或子文档字段。

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    在 MongoDB 2.4 中,您无法在聚合框架中实现任何自定义函数。如果您想通过一个或多个字段来$group,则需要通过聚合运算符和表达式添加它们,或者如果您不想每次都计算,则需要通过显式 update() 来添加它们。

    使用聚合框架,您可以使用$cond operator 在$project 管道步骤中添加计算的bucket 字段。

    下面是一个基于 numberField 计算范围的示例,然后可以在 $group 管道中用于 sum/avg/etc:

    db.data.aggregate(
        { $project: {
            numberfield: 1,
            someotherfield: 1,
            bucket: {
                $cond: [ {$and: [ {$gte: ["$numberfield", 1]}, {$lte: ["$numberfield", 20]} ] }, '1-20', {
                $cond: [ {$lt: ["$numberfield", 41]},  '21-40',  {
                $cond: [ {$lt: ["$numberfield", 61]},  '41-60',  {
                $cond: [ {$lt: ["$numberfield", 81]},  '61-80',  {
                $cond: [ {$lt: ["$numberfield", 101]}, '81-100', '100+' ]
                }]}]}]}]
            }
        }},
        { $group: {
            _id: "$bucket",
            sum: { $sum: "$someotherfield" }
        }}
    )
    

    【讨论】:

      猜你喜欢
      • 2021-06-15
      • 2013-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多