What is the performance difference between cursor and aggregation?

127 views
Skip to first unread message

RaR

unread,
Sep 28, 2016, 3:32:59 AM9/28/16
to mongodb-user
Hi,

I am new to mongodb. I am trying to do some aggregation operations like sum, avg, min.. on a collection. And I found that I can do it either using aggregation framework or cursor.forEach(). Which one to use? It will be better if someone explains how both works internally and give me some suggestions. Thank you in advance

Lungang Fang

unread,
Oct 10, 2016, 7:38:12 AM10/10/16
to mongodb-user

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

RaR

unread,
Nov 30, 2016, 5:09:38 AM11/30/16
to mongodb-user
It got me clear. find() transfers all documents into application, and we have to iterate over it. Aggregation framework will do it at at mongodb server level. Nice point. Thank you!
Reply all
Reply to author
Forward
0 new messages