Group (By) in Mongoose?

后端 未结 4 1200
盖世英雄少女心
盖世英雄少女心 2021-02-12 15:18

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(         


        
4条回答
  •  天涯浪人
    2021-02-12 15:33

    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

提交回复
热议问题