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

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


当前回答

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

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

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

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

其他回答

你可以试试这个方法:

获取集合中记录的总数

db.dbcollection.count() 

然后使用skip:

db.dbcollection.find().skip(db.dbcollection.count() - 1).pretty()

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

例子:

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

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

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

根据集合的大小,排序、跳过等操作可能会非常慢。

如果您根据某些标准对集合进行索引,则可以获得更好的性能;然后你可以使用min()游标:

首先,使用db.collectionName索引集合。setIndex(yourIndex) 你可以使用升序或降序,这很酷,因为你总是想要“最后N项”……所以如果你按降序索引,就相当于得到“前N项”。

然后你找到你的集合的第一项,并使用它的索引字段值作为搜索的最小条件,如下所示:

db.collectionName.find().min(minCriteria).hint(yourIndex).limit(N)

下面是min()游标的引用:https://docs.mongodb.com/manual/reference/method/cursor.min/

使用$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条记录。