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

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


当前回答

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

其他回答

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

最后一个函数应该是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();

你可以试试这个方法:

获取集合中记录的总数

db.dbcollection.count() 

然后使用skip:

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

如果我理解了你的问题,你需要按升序排序。

假设你有一些id或日期字段称为“x”,你会做…

.sort ()


db.foo.find().sort({x:1});

1将升序排序(从最老到最新),而-1将降序排序(从最新到最老)。

如果你使用自动创建的_id字段,它有一个日期嵌入其中…所以你可以用它来订购…

db.foo.find().sort({_id:1});

这将返回从最老到最新排序的所有文档。

自然秩序


你也可以使用上面提到的自然顺序……

db.foo.find().sort({$natural:1});

同样,使用1或-1取决于你想要的顺序。

使用.limit ()


最后,在执行这种广泛开放的查询时添加一个限制是一个很好的实践,这样你就可以这样做…

db.foo.find().sort({_id:1}).limit(50);

or

db.foo.find().sort({$natural:1}).limit(50);