Database Reference
In-Depth Information
aggregator.reviews += 1.0;
aggregator.votes
+= doc.votes;
}
You can see that the initial document defines the values that you want for each group-
ing key. In other words, once you've run group , you want a result set that, for each
user_id , gives you the total number of reviews written and the sum of votes for all
those reviews. The work of generating those sums is done by the reduce function. Sup-
pose I've written five reviews. This means that five review documents will be tagged
with my user ID . Each of those five documents will be passed to the reduce function as
the doc argument. At first the value of aggregator is the initial document. Succes-
sive values are added to the aggregator for each document processed.
Here's how you'd execute this group command from the JavaScript shell.
Listing 5.1
Using MongoDB's group command
results = db.reviews.group({
key: {user_id: true},
initial: {reviews: 0, votes: 0.0},
reduce:
function(doc, aggregator) {
aggregator.reviews += 1;
aggregator.votes
+= doc.votes;
}
finalize: function(doc) {
doc.average_votes = doc.votes / doc.reviews;
}
})
You should note that you've passed an extra argument to group . You originally wanted
the average number of votes per review. But this average can't be calculated until you
have the total number of votes for all reviews and the total number of reviews. This is
what the finalizer is for. It's a JavaScript function that's applied to each grouped result
before the group command returns. In this case, you use the finalizer to calculate the
average number of votes per review.
Here are the results of running this aggregation on a sample data set.
Listing 5.2
Results of the group command
[
{user_id: ObjectId("4d00065860c53a481aeab608"),
votes: 25.0,
reviews: 7,
average: 3.57
},
{user_id: ObjectId("4d00065860c53a481aeab608"),
votes: 25.0,
reviews: 7,
average: 3.57
}
]
 
Search WWH ::




Custom Search