对集合中的所有键运行map reduce-mongodb [英] Run map reduce for all keys in collections - mongodb

查看:54
本文介绍了对集合中的所有键运行map reduce-mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在mongodb中使用map reduce来查找像这样的客户的订单数量

i am using map reduce in mongodb to find out the number of orders for a customer like this

db.order.mapReduce(
    function() {
        emit (this.customer,{count:1})
    },
    function(key,values){
        var sum =0 ; 
        values.forEach(
            function(value) {
                sum+=value['count'];
            }
        ); 
        return {count:sum};
    },
    {
         query:{customer:ObjectId("552623e7e4b0cade517f9714")},
         out:"order_total"
    }).find()

这给了我这样的输出

{ "_id" : ObjectId("552623e7e4b0cade517f9714"), "value" : { "count" : 13 } }

当前,它只为一个客户服务,这是关键.现在,我希望它运行此地图,以减少订单集合中所有客户的查询,并输出所有类似此单个输出的结果.有什么方法可以按顺序为所有客户做到这一点?

Currently it is working for a single customer which is a key. Now i want this to run this map reduce query for all customers in order collection, and output the result for all like this single output. Is there any way through which I can do it for all customers in order?

推荐答案

为该简单任务使用地图/缩小功能有点像使用(相对较慢的)大锤砸破螺母.聚合框架基本上是为这种简单的聚合而发明的(并且可以为您!):

Using a map/reduce for that simple task is a bit like using a (comparatively slow) sledgehammer to crack a nut. The aggregation framework was basically invented for this kind of simple aggregation (and can do a lot more for you!):

db.order.aggregate([
    { "$group":{ "_id":"$customer", "orders":{ "$sum": 1 }}},
    { "$out": "order_total"}
])

根据您的用例,您甚至可以省略 $ out 阶段并直接使用结果.

Depending on your use case, you can even omit the $out stage and consume the results directly.

> db.orders.aggregate([{ "$group":{ "_id":"$customer", "orders":{ "$sum": 1 }}}])
{ "_id" : "b", "orders" : 2 }
{ "_id" : "a", "orders" : 3 }

请注意,对于非常大的集合,此方法很可能不适合,因为它需要花费一些时间(但仍应比map/reduce操作更快).

Note that with very large collections, this most likely is not suitable, as it make take a while (but it should still be faster than a map/reduce operation).

要查找单个客户的订单数量,您可以使用简单的查询并使用 cursor.count()方法:

For finding the number of orders of a single customer, you can use a simple query and use the cursor.count() method:

> db.orders.find({ "customer": "a" }).count()
3

这篇关于对集合中的所有键运行map reduce-mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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