在MongoDB中获取特定字段平均值的最快方法 [英] Fastest way to get the average of a specific field in MongoDB

查看:790
本文介绍了在MongoDB中获取特定字段平均值的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类似以下的数据集:

Let's say I have a dataset like the following:

{ "_id" : ObjectId("4dd51c0a3f42cc01ab0e6506"), "views" : 1000, "status" : 1 }
{ "_id" : ObjectId("4dd51c0e3f42cc01ab0e6507"), "views" : 2000, "status" : 1 }
{ "_id" : ObjectId("4dd51c113f42cc01ab0e6508"), "views" : 3000, "status" : 1 }
{ "_id" : ObjectId("4dd51c113f42cc01ab0e6508"), "views" : 4000, "status" : 0 }

获取状态为1的所有文档的平均视图数的最快方法(性能)是什么?像这样的基本操作是否需要Map/Reduce?还是有另一种方法?

What is the fastest way (performance-wise) to get the average number of views for all documents with a status of 1? Is Map/Reduce required for something basic like this, or is there another way?

推荐答案

使用组: http://www.mongodb.org/display/DOCS/Aggregation

您需要一个文件柜台和一个用于视图总数的柜台.最后,您只需要对这两个数字进行除法即可.

you need a counter for the documents and another for the sum of views. In finalize you just do a division on these two numbers.

db.test.group(
   { cond: {"status": 1}
   , initial: {count: 0, total:0}
   , reduce: function(doc, out){ out.count++; out.total += doc.views }
   , finalize: function(out){ out.avg = out.total / out.count }
} );

这篇关于在MongoDB中获取特定字段平均值的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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