tags:

views:

41

answers:

1

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?

+2  A: 

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.

Gates VP
I have to do it on every page load, which may be "a lot" I guess. So basically from what I understand, it is too expensive to get this data in real time? Do I have to setup a cron job to run the Map/Reduce periodically?
Brainfeeder
MapReduce in mongodb isn't very fast.
TTT
Yeah, every page load is way too often. You'll definitely want to schedule a cron for the M/R.
Gates VP