我在使用 MongoDB Node.js native 驱动程序版本 2.2.29 时遇到问题。
这是我正在运行的代码:
let cursor = db.collection( 'log' )
.find({timestamp: { '$lte': 1498556839 }})
.sort( { create_date_ttl: -1 } )
.limit( 3 );
如果我现在运行 cursor.count()
并处理 Promise,我会看到计数为我提供了 56 条记录而不是 3 条(指定的限制)。
cursor.count().then( (count) => {
// count here is 56
});
但是,如果我使用回调运行 cursor.count( function (err, count) {})
,则只有 3 条记录是正确的。
cursor.count( function (err, count) {
// count here is 3 according to the limit specified.
});
有没有人遇到同样的问题或者有人可以解释我这怎么可能?也许我遗漏了什么,但根据官方的说法似乎没问题documentation .
提前致谢。
最佳答案
明确设置第一个参数 (applySkipLimit
) 为真,然后 skip
和 limit
将被应用。
cursor.count(true).then( (count) => {
// count here will be 3
});
似乎文档没有明确说明,因为写着 true 应该是默认值。如评论中所述,这是回调的行为。
关于Node.js MongoDB 驱动游标计数不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44777576/