mongodb聚合框架-从函数生成_id [英] mongodb aggregation framework - generate _id from function

查看:175
本文介绍了mongodb聚合框架-从函数生成_id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在$ group的_id字段中使用自定义函数?尽管文档似乎表明可以计算该字段,但我无法使其正常运行.

Is it possible to have a custom function in the _id field in $group? I couldn't make it work although the documentation seems to indicate that the field can be computed.

例如,假设我有一组文档,其数字字段的范围是1到100. 1-20、21-40等.然后,我将使用此存储段标识符求和/平均一个不同的字段.因此,我正在尝试执行此操作:

For example, let's say I have a set of documents having a number field that ranges 1 to 100. I want to classify the number into several buckets e.g. 1-20, 21-40, etc. Then, I will sum/avg a different field with this bucket identifier. So I am trying to do this:

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

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

...where bucket is a function that returns a string e.g. "1-20".

那行不通.

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

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

推荐答案

与MongoDB 2.4一样,您不能在Aggregation Framework中实现任何自定义功能.如果要按一个或多个字段$group,则需要通过聚合运算符和表达式或不希望每次进行计算的显式update()来添加它们.

As at MongoDB 2.4, you cannot implement any custom functions in the Aggregation Framework. If you want to $group by one or more fields, you need to add those either through aggregation operators and expressions or via an explicit update() if you don't want to calculate each time.

使用Aggregation Framework,您可以使用

Using the Aggregation Framework you can add a computed bucket field in a $project pipeline step with the $cond operator.

以下是根据numberField计算范围的示例,然后可将其用于$group管道中的sum/avg/etc:

Here is an example of calculating ranges based on numberField that can then be used in a $group pipeline for 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" }
    }}
)

这篇关于mongodb聚合框架-从函数生成_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆