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

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


当前回答

最后添加的N条记录,从最近的到最近的,可以用这个查询看到:

db.collection.find().skip(db.collection.count() - N)

如果你想把它们的顺序颠倒:

db.collection.find().sort({ $natural: -1 }).limit(N)

如果你安装了Mongo-Hacker,你还可以使用:

db.collection.find().reverse().limit(N)

如果你厌倦了一直写这些命令,你可以在你的~/.mongorc.js中创建自定义函数。如。

function last(N) {
    return db.collection.find().skip(db.collection.count() - N);
}

然后在mongo shell中输入last(N)

其他回答

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

最后一个函数应该是sort,而不是limit。

例子:

db.testcollection.find().limit(3).sort({timestamp:-1}); 

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

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

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

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

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

使用$slice操作符限制数组元素

GeoLocation.find({},{name: 1, geolocation:{$slice: -5}})
    .then((result) => {
      res.json(result);
    })
    .catch((err) => {
      res.status(500).json({ success: false, msg: `Something went wrong. ${err}` });
});

其中geolocation是数据数组,从中我们得到最近5条记录。