ySgPjx
ySgPjx

Reputation: 10245

Limit results of group() in MongoDB

How can I limit the number of results when using group() in MongoDB? Basically I'm looking for the equivalent of this MySQL query:

SELECT * FROM items GROUP BY type LIMIT 5;

Edit: I just realized this can be done with Map/Reduce, but I read that using Map/Reduce on a single server (my case) is a bit overkill. Is it true? Ultimately, what's the best way to achieve what I need?

Upvotes: 2

Views: 2190

Answers (1)

Gates VP
Gates VP

Reputation: 45277

The problem with group is that it won't really do this. It simply returns an array of all of the groups.

You can use a Map / Reduce to solve this problem by:

  1. Issuing the Map / Reduce (into a temp or permanent collection)
  2. Performing a find on that collection with a .limit(5) on the cursor that is returned

Map / Reduce on a single server is not overkill with MongoDB. However, you are working the "speed / space" trade-off. You can theoretically run a temporary map-reduce every time you need this data. However if you do this a lot, you'll probably want to schedule the map-reduce and query the store as map-reduces are not cheap.

Upvotes: 5

Related Questions