In my tests it also proved to be about 4x faster than a similar MapReduce, however, it comes with a severe cost: It blocks all reading from the collection. This is a huge problem and basically makes it worthless for doing serious queries on a database with say hundreds of thousands of users like I have in my day job. From what I can tell finds, distincts, and mapReduces don't block and some combination of those provide non-blocking alternatives.
Here's a simple map reduce example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// groups users by type | |
var map = function() { | |
emit(this.type, 1) | |
} | |
var reduce = function(key, values) { | |
var result = 0 | |
values.forEach(function(value) { | |
result += value | |
}) | |
return result | |
} | |
var options = {out:{inline:1}} | |
db.users.mapReduce(map, reduce, options) |
One more note, I recently read MongoDB: The Definitive Guide, which had a lot of examples and clarification that are not readily available in the online documentation. I highly suggest checking it out!
Worth noting that group blocking appears to be fixed as of 1.9.2 - https://jira.mongodb.org/browse/SERVER-1395
ReplyDelete