Zach
Zach

Reputation: 19112

What's the best way to find the most frequently occurring value in MongoDB?

I'm looking for the equivalent of this sort of SQL query.

SELECT field, count(*) as counter from table order by counter DESC

What's the best way to achieve this?

Thanks

Upvotes: 2

Views: 3770

Answers (2)

mnemosyn
mnemosyn

Reputation: 46331

I'd handle aggregation queries by keeping track of the respective counts separately, i.e. in their own collection. This way, you can simply query the "most frequently occurring" collection. Downside: you need to perform another write whenever the data changes.

Of course, you could also update that collection from time to time using Map/Reduce. This depends a bit on how accurate the information must be and how often it changes.

Make sure, however, not to call the Map/Reduce operation very often: It is not meant to be used in an interactive fashion (i.e. not in every page view) but rather scarcely in an offline process that updates the counts every hour or so. Hence, if your counts change very quickly, use a counters collection.

Upvotes: 1

Ian Mercer
Ian Mercer

Reputation: 39297

Use Map-Reduce. Map each document by emitting the key and a value 1, then aggregate them using a simple reduce operation. See http://www.mongodb.org/display/DOCS/MapReduce

Upvotes: 4

Related Questions