Hi there,
And I found that I can do it either using aggregation framework or cursor.forEach(). Which one to use?
I am assuming that you are asking the difference between using Group Accumulator Operators and using the cursor returned by db.collection.find().
The aggregation framework is used to perform a series of transformations on a set of documents, where a typical use of the aggregation pipeline is to perform “$group” accumulation operations such as sum, average, count, etc. The calculations required for those operations are handled by the MongoDB server via the aggregation framework, hence it may simplify your application code and error handling since you don’t have to do such calculations in your code.
In contrast, if you use db.collection.find()
, MongoDB simply returns all documents matching your search criteria. It is you (the application) that is responsible for iterating the result (using a cursor) to do your calculation. You would have to catch any exception during the process. Another downside is that transferring all documents of query result via network only to get the average (or min/max etc.) may not be bandwidth-efficient if the number of documents is quite large.
By the way, please note that since MongoDB 2.6, aggregation can also return a cursor, which is similar to the cursor returned by db.collection.find()
. It allows you to iterate over all the documents produced by the final stage of aggregation pipelined.
Regards,
Lungang