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

查看:21
本文介绍了如何对 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> 是您在 emit 中提供的任何值.

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;
}

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

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天全站免登陆