如何对MongoDB集合中所有文档的键值求和 [英] How to sum the value of a key across all documents in a MongoDB collection

查看:76
本文介绍了如何对MongoDB集合中所有文档的键值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoDB中有集合:

I have collection in MongoDB:

{ "_id" : ObjectId("4d2407265ff08824e3000001"), "subida" : 3.95 }
{ "_id" : ObjectId("4d2551b4ae9fa739640df821"), "subida" : 6.03 }
{ "_id" : ObjectId("4d255b115ff08821c2000001"), "subida" : 5.53 }
{ "_id" : ObjectId("4d25e8d55ff08814f8000001"), "subida" : 1.96 }

如何在所有文档中求和键值,例如"subida"?有了以上文件,我应该会收到以下类似的信息:

How I can sum the value of a key, e.g., "subida", across all documents? With the documents above, I should receive something along the lines of:

{ "subida" : 17.47 }

推荐答案

我亲自对集合进行mapreduce:

I'd personally perform a mapreduce on the collection :

map是发出"subida"字段的简单函数.如果您需要一个总和,则密钥应相同; reduce之后的结果将产生单个对象{<key>: <sum>},其中<key>是您在发射中提供的任何值.

map is a simple function emitting the "subida" field. The key should the same if you need a single sum; the result after reduce will yield the single object {<key>: <sum>}, with <key> being whatever value you supplied in the emit.

map = function() { emit(<key>, this.subida); }

reduce也是将它们相加的简单函数:

reduce is also a simple function summing them :

red = function(k, v) {
  var i, sum = 0;
  for (i in v) {
    sum += v[i];
  }
  return sum;
}

然后您可以在集合<mycollection>上调用mapreduce:

You can then call mapreduce on your collection <mycollection>:

res = db.<mycollection>.mapReduce(map, red);

这将创建一个您可以像其他任何集合一样操作的临时新集合. mapReduce返回的值包含有关mapReduce的多个值,例如所花费的时间,状态...以及温度.在结果"字段中创建的集合名称. 要获取所需的值,必须查询该集合:

Which will create a temporary new collection you can manipulate like any other collection. The value returned by mapReduce holds several values regarding the mapReduce such as the time taken, status..., as well as the temp. collection name created in the "result" field. To get the values you need, you have to query that collection :

db[res.result].find()

应该给您对象{<key>: <sum>}.

如果运行MongoDB 1.7.4或更高版本,则可以通过要求MongoDB直接返回结果而不创建集合来节省一些麻烦:

If you run MongoDB 1.7.4 or higher, you can save you a bit of hassle by asking MongoDB to return the result directly without creating a collection :

db.<mycollection>.mapReduce(map, red, {out : {inline: 1}});

这篇关于如何对MongoDB集合中所有文档的键值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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