【问题标题】:MongoDB: current sum of fieldsMongoDB:当前字段总和
【发布时间】:2014-10-06 09:43:36
【问题描述】:

我们有文件

{a: 1}
{a: 5}
{a: 3}

如何通过计算当前总和来聚合数据?

{a: 1, cs: 1}
{a: 5, cs: 6}
{a: 3, cs: 9}

【问题讨论】:

  • db.c.aggregate({_id:'$a', cs: {$sum: 1}}) 从你的问题来看,除非计数来自其他地方

标签: javascript mongodb mapreduce mongodb-query


【解决方案1】:

您目前只能在 MongoDB 中使用 mapReduce 执行此类操作。原因是这是目前唯一可以容纳“全局”变量的地方,而这基本上是“运行总计”所需要的:

db.collection.mapReduce(
    function(){ 
        totals += this.a;
        emit(this._id, {"a": this.a, "cs": totals});
    },
    function() {},  // nothing to reduce here
    {
        "out": { "inline": 1 },
        "scope": { "totals": 0 }
    }
);

所以“这里没有实际的分组”,但如果你愿意,你可以这样做。关键是这维护了每条记录的“运行总数”,这就是您似乎要问的。

"mapReduce" 命令有一个称为“作用域”的方面,用于实现可用于此类任务的“全局”变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 2023-01-13
    • 2021-07-03
    • 2021-04-15
    • 1970-01-01
    相关资源
    最近更新 更多