The fastest way to get average value for a specific area in MongoDB

Let's say I have a data set, for example:

{ "_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 (in terms of performance) to get the average number of views for all documents with status 1? Is Map / Reduce required for something basic, or is there another way?

+6
source share
2 answers

Use Group: http://www.mongodb.org/display/DOCS/Aggregation

you need a counter for documents, and another for the amount of views. In final mode, you simply do the division into 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 } } ); 
+7
source

A faster way to get the average value in any case is to pre-calculate it (maybe you can do it in the background) and create an additional field / collection to store it.

+5
source

Source: https://habr.com/ru/post/890940/


All Articles