mongodb aggregation framework - generate _id from function

前端 未结 1 1298
南笙
南笙 2021-01-17 01:11

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条回答
  • 2021-01-17 01:41

    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.

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

    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" }
        }}
    )
    
    0 讨论(0)
提交回复
热议问题