【问题标题】:MongDb Summing up over dictionary elementsMongoDb 总结字典元素
【发布时间】:2014-11-07 17:02:51
【问题描述】:

您好,我有一个具有以下结构的文档,我想对所有城市中所有不同水果的 $ 进行总和,因此输出为 { fruits : { apples : $9, grapes : $15, pears : $14 , oranges : $20 } }

db.fruitmarket

{ _id:1 市场名称 : LA, 水果:{苹果:2美元,葡萄:3美元,梨:4美元,橙子:5美元}

_id:1 市场名称 : CHI, 水果:{苹果:3美元,葡萄:5美元,梨:4美元,橙子:7美元}

_id:1 市场名称:纽约, 水果:{苹果:4美元,葡萄:7美元,梨:6美元,橙子:8美元}

}

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    更新答案

    首先,为了确保我可以对此进行测试,我创建了一个包含水果信息的集合并插入了您的示例数据:

    db.fruitmarket.insert(
       [
           { marketname : "LA", fruit : { apples : 2, grapes : 3 , pears : 4, oranges : 5} },
           { marketname : "CHI", fruit : { apples : 3, grapes : 5 , pears : 4, oranges : 7} },
           { marketname : "NY", fruit : { apples : 4, grapes : 7 , pears : 6, oranges : 8} }
       ]
    )
    

    ma​​p 函数,为每个文档发出 fruit 键的所有属性:

    function() {
        for (var key in this.fruit) {
            emit(key, this.fruit[key]);
        }
    }
    

    reduce 函数,对所有 fruit 值求和:

    function(key, values) {
        return Array.sum(values);
    }
    

    最后,我运行了 map-reduce:

    db.loadServerScripts();
    db.fruitmarket.mapReduce(mapSubProperties, reduceSubProperties, { out: "fruits"})
    

    我得到了你想要的结果:

    /* 0 */
    {
        "_id" : "apples",
        "value" : 9
    }
    
    /* 1 */
    {
        "_id" : "grapes",
        "value" : 15
    }
    
    /* 2 */
    {
        "_id" : "oranges",
        "value" : 20
    }
    
    /* 3 */
    {
        "_id" : "pears",
        "value" : 14
    }
    

    【讨论】:

    • 如果我事先不知道键值,我该如何处理聚合。我可以写一些更通用的东西吗?所有“水果”都是事先不知道的。
    • 我试图寻找方法来做到这一点,但看起来只有当 fruits 对象存储一组值时才有可能。如果所有这些都在一个数组中,您可以使用 Map-Reduce 或 $unwind 聚合来完成您正在尝试做的事情。或者,您可以尝试对水果的属性使用 for 循环,但我不确定
    • 所以我不确定我是否完全理解此问题/答案中提出的解决方案 - stackoverflow.com/questions/2997004/… - 但我认为这更接近于回答您的问题。此外,您的解决方案实际上可能看起来更简单,因为您不必担心案例中的递归 - 您已经知道所有水果都在您的“水果”键中,对吧?
    • @krish727 - 查看更新后的答案。这个答案比我最初的回答要好得多,因为它遍历了“水果”子文档中的所有内容,然后返回每种水果的总美元价值。
    猜你喜欢
    • 1970-01-01
    • 2020-04-08
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 2015-05-05
    相关资源
    最近更新 更多