Database Reference
In-Depth Information
keyf —A JavaScript function that, when applied to a document, generates a key
for that document. This is useful when the key for grouping needs to be calcu-
lated. For instance if you wanted to group a result set by the day of the week
each document was created on but didn't actually store that value, then you
could use a key function to generate the key:
function(doc) {
return {day: doc.created_at.getDay();
}
This function will generate keys like this one: {day: 1} . Note that keyf is
required if you don't specify a standard key .
initial —A document that will be used as the starting basis for the results of
the aggregation. When the reduce function is first run, this initial document
will be used as the first value of the aggregator and will usually contain all the
keys you aggregate over. So, for instance, if you're calculating sums of votes and
total documents for each grouped item, then your initial document will look
like this: {vote_sum: 0.0, doc_count: 0} .
Note that this parameter is required.
reduce —A JavaScript function to perform the aggregation. This function will
receive two arguments: the current document being iterated and an aggregator
document to store the results of the aggregation. The initial value of the aggre-
gator will be the value of the initial document. Here's a sample reduce func-
tion aggregating votes and view sums:
function(doc, aggregator) {
aggregator.doc_count += 1;
aggregator.vote_sum += doc.vote_count;
}
Note that the reduce function doesn't need to return anything; it merely needs
to modify the aggregator object. Note also that the reduce function is required.
cond —A query selector that filters the documents to be aggregated over. If you
don't want your group operation to process the entire collection, then you must
supply a query selector. For example, if you wanted to aggregate over only those
documents having more than five votes, you could provide the following query
selector: {vote_count: {$gt: 5}}
finalize —A JavaScript function that will be applied to each result document
before returning the result set. This function gives you a way to post-process the
results of a group operation. A common use is averaging. You can use the exist-
ing values in a grouped result to add another value to store the average:
function(doc) {
doc.average = doc.vote_count / doc.doc_count;
}
group is admittedly tricky at first, what with all the options just presented. But with a
little practice, you'll quickly grow accustomed to its ways.
Search WWH ::




Custom Search