Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between aggregate ($match) and find, in MongoDB?

Tags:

mongodb

What is the difference between the $match operator used inside the aggregate function and the regular find in Mongodb?

Why doesn't the find function allow renaming the field names like the aggregate function? e.g. In aggregate we can pass the following string:

{ "$project" : { "OrderNumber" : "$PurchaseOrder.OrderNumber" , "ShipDate" : "$PurchaseOrder.ShipDate"}}

Whereas, find does not allow this.

Why does not the aggregate output return as a DBCursor or a List? and also why can't we get a count of the documents that are returned?

Thank you.

like image 418
user2383313 Avatar asked May 14 '13 20:05

user2383313


People also ask

What is difference between find and match in MongoDB?

With a main difference that match is used in aggregation framework whereas, find is not. If you just want to do a 'straight' find, then the find function is okay to use. On the other hand, if you want to do more, this is where the Aggregate framework steps in.

Is MongoDB aggregate faster than find?

The aggregation query takes ~80ms while the find query takes 0 or 1ms.

What does match do in MongoDB?

The MongoDB $match operator filters the documents to pass only those documents that match the specified condition(s) to the next pipeline stage.


1 Answers

Why does not the aggregate output return as a DBCursor or a List?

The aggregation framework was created to solve easy problems that otherwise would require map-reduce.

This framework is commonly used to compute data that requires the full db as input and few document as output.

What is the difference between the $match operator used inside the aggregate function and the regular find in Mongodb?

One of differences, like you stated, is the return type. Find operations output return as a DBCursor.

Other differences:

  • Aggregation result must be under 16MB. If you are using shards, the full data must be collected in a single point after the first $group or $sort.
  • $match only purpose is to improve aggregation's power, but it has some other uses, like improve the aggregation performance.

and also why can't we get a count of the documents that are returned?

You can. Just count the number of elements in the resulting array or add the following command to the end of the pipe:

{$group: {_id: null, count: {$sum: 1}}}

Why doesn't the find function allow renaming the field names like the aggregate function?

MongoDB is young and features are still coming. Maybe in a future version we'll be able to do that. Renaming fields is more critical in aggregation than in find.

EDIT (2014/02/26):

MongoDB 2.6 aggregation operations will return a cursor.

EDIT (2014/04/09):

MongoDB 2.6 was released with the predicted aggregation changes.

like image 165
vinipsmaker Avatar answered Oct 22 '22 16:10

vinipsmaker