I\'ve constructed the query I want in the shell but am having trouble writing it in Mongoose.
db.commentstreams.group({ key: { page_id: true }, reduce: function(
MapReduce should be the proper way to go but if you're not sharding and your query won't result in more than 10k records its ok.
You can access any node-mongodb-native functions through moongoose, so it looks like this:
var group = {
key: {},
cond: {item_id: item_id},
reduce: function(doc, out) {
out.count++;
out.total += doc.value;
},
initial: {
total: 0,
count: 0
},
finalize: function(out) {
out.avg = out.total / out.count;
}
};
Item.collection.group(group.key, group.cond, group.initial, group.reduce, group.finalize, true, function(err, results) {
console.log('group results %j', results);
});
node-mongodb-native source: https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js#L1165
MongoDB group doc: http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Group