【问题标题】:Normalizing results from MongoDB标准化 MongoDB 的结果
【发布时间】:2014-12-21 14:24:27
【问题描述】:

我需要对 MongoDB 表执行以下操作。我需要根据某些列值过滤文档,我需要按列分组并根据聚合找到值的计数。此外,我想标准化计数值(即,将结果的计数值除以该结果的最大计数值)。

我已经通过使用聚合管道的 $match$group 参数完成了前两个步骤。我不确定如何对结果部分进行规范化。

我当前的查询看起来像这样

db.list_input_file.aggregate([ 
 {$match:{ 'content.Year' : {$eq : '2006'} }}, 
 {$group:{'_id':'$content.Author', count:{$sum:1}}} 
])

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    我认为可以通过(代码中的解释)来完成

    db.list_input_file.aggregate([ {
        $match : {
            'content.Year' : {
                $eq : '2006'
            }
        }
    }, {
        $group : {
            '_id' : '$content.Author',
            count : {
                $sum : 1
            }
        }
    }, {
        $group : {
            _id : 0,
            maxCount : {            // get the largest count value
                $max : "$count"
            },
            docs : {                // push all documents into one field to store as an array
                $push : "$$ROOT"
            }
        }
    }, {
        $project : {
            _id : 0,
            docs : {
                $map : {
                    "input" : "$docs",
                    "as" : "e",
                    "in" : {                    // retrieve each element
                        _id : "$$e._id",
                        count : "$$e.count",
                        rate : {                // add the normalized value here
                            $divide : [ "$$e.count", "$maxCount"]
                        }
                    }
                }
            }
        }
    }, {
        $unwind : "$docs"
    }, {
        $project : {
            _id : "$docs._id",
            count : "$docs.count",
            rate : "$docs.rate"
        }
    } ]);
    

    【讨论】:

    • 哇!感谢那。我自己永远无法弄清楚这一点!
    猜你喜欢
    • 2012-07-02
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    • 2019-08-02
    • 2014-03-10
    • 2015-03-25
    相关资源
    最近更新 更多