2016-02-15 102 views
1

從MongoDB的光標限制的文檔如何重置MongoDB的聚集限制

A limit() value of 0 (i.e. .limit(0)) is equivalent to setting no limit.

但我不能找到辦法在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: the limit must be positive

謝謝回覆!

回答

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