我找不到任何地方有这样的记录。默认情况下,find()操作将从头获取记录。我怎么能得到mongodb的最后N条记录?

编辑:我也想返回的结果从最近到最近的顺序,而不是相反。


当前回答

db.collection.find().hint( { $natural : -1 } ).sort(field: 1/-1).limit(n)

根据mongoDB文档:

您可以指定{$natural: 1}强制查询执行转发集合扫描。 您还可以指定{$natural: -1}来强制查询执行反向收集扫描。

其他回答

你可能想要使用find选项: http://docs.meteor.com/api/collections.html#Mongo-Collection-find

db.collection.find({}, {sort: {createdAt: -1}, skip:2, limit: 18}).fetch();

您不能根据集合的大小“跳过”,因为它不会考虑查询条件。

正确的解决方案是从期望的端点开始排序,限制结果集的大小,然后在必要时调整结果的顺序。

下面是一个基于实际代码的示例。

var query = collection.find( { conditions } ).sort({$natural : -1}).limit(N);

query.exec(function(err, results) {
    if (err) { 
    }
    else if (results.length == 0) {
    }
    else {
        results.reverse(); // put the results into the desired order
        results.forEach(function(result) {
            // do something with each result
        });
    }
});

如果你使用MongoDB compass,你可以使用sort field来过滤,

db.collection.find().hint( { $natural : -1 } ).sort(field: 1/-1).limit(n)

根据mongoDB文档:

您可以指定{$natural: 1}强制查询执行转发集合扫描。 您还可以指定{$natural: -1}来强制查询执行反向收集扫描。

查看查询:排序和自然顺序,http://www.mongodb.org/display/DOCS/Sorting+and+Natural+Order 以及游标方法下的sort() http://www.mongodb.org/display/DOCS/Advanced+Queries