mponizil
mponizil

Reputation: 201

Group (By) in Mongoose?

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(obj,prev) { prev.num_comments += obj.num_comments }, initial: { num_comments: 0 } })

I'm a bit confused by the Mongoose syntax; perhaps someone could shed some light on this one. Much thanks.

Upvotes: 19

Views: 22064

Answers (4)

Esteban Preciado
Esteban Preciado

Reputation: 81

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)
});

Upvotes: 0

Gabriel Wu
Gabriel Wu

Reputation: 2086

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.

Upvotes: 0

Bruno Fuster
Bruno Fuster

Reputation: 486

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

Upvotes: 13

andyuk
andyuk

Reputation: 39108

According to this post:

Model.find({}, [fields], {'group': 'FIELD'}, function(err, logs) { 
        ... 
}); 

Unfortunately we seem to be lacking documentation for this one.

Upvotes: 15

Related Questions