Group (By) in Mongoose?

后端 未结 4 1206
盖世英雄少女心
盖世英雄少女心 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

    0 讨论(0)
  • 2021-02-12 15:42

    According to this post:

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

    Unfortunately we seem to be lacking documentation for this one.

    0 讨论(0)
  • 2021-02-12 15:42

    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)
    });
    
    0 讨论(0)
  • 2021-02-12 15:44

    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.

    0 讨论(0)
提交回复
热议问题