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
According to this post:
Model.find({}, [fields], {'group': 'FIELD'}, function(err, logs) {
...
});
Unfortunately we seem to be lacking documentation for this one.
I worked with similar example, I hope this be helpful
Register.aggregate(
[
{
$group: {_id: {campaign: "$campaign"}, quantity: {$sum: 1}}
},
{
$limit: 5
},
{
$sort: {date: -1}
}
], function (err, res) {
console.log(res)
});
if you're trying to use Mongoose to group maybe you're better take a look at this Mongoose group query in node.js / express route
It seems group is not supported by Mongoose while aggregate is.