【问题标题】:How to reset mongodb aggregation limit如何重置mongodb聚合限制
【发布时间】:2023-04-07 12:07:01
【问题描述】:

来自 mongodb 游标限制的文档

limit() 值为 0(即 .limit(0))相当于设置 no 限制。

但我找不到在mongodb aggregation limit docs 中重置查询限制的方法。

 const listQuery = query.limit(20).exec(); //  I need limit here
 query.limit(0); // error here
 const totalQuery = query.group(....).exec(); // No limit must be specified

我遇到错误

MongoError:限制必须是正数

感谢回复!

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    我编写了从聚合中重置任何管道命令的函数

    Aggregate.prototype.reset = function (command, onlyLatest) {
      command = command.replace(/^/, '$');
      let i   = this._pipeline.length;
      while (i--) {
        if (command === Object.keys(this._pipeline[i])[0]) {
          this._pipeline.splice(i, 1);
          if (onlyLatest) {
            break;
          }
        }
      }
      return this;
    };
    

    示例,在有分页时很有用

      var query = this.aggregate();
      query.match({ ... });
      query.lookup({ ... });
      query.unwind({ ... });
      query.project({ ... });
      query.sort(...);
      query.skip();
      query.limit(10);
    
      const listQuery  = query.exec();
      const totalQuery = query.reset('limit').reset('skip').exec();
    
      return Promise.all([listQuery, totalQuery]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-08
      • 2020-06-11
      • 2014-08-26
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 2013-12-05
      • 1970-01-01
      相关资源
      最近更新 更多