Fastest way to get the average of a specific field in MongoDB

▼魔方 西西 提交于 2020-02-03 05:22:51

问题


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 }

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?


回答1:


Use group: 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 }
} );



回答2:


Faster way to get average in any case - precalculate it(probably you can do this in background) and create extra field/collection to store it.



来源:https://stackoverflow.com/questions/6414312/fastest-way-to-get-the-average-of-a-specific-field-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!