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

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


当前回答

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

根据mongoDB文档:

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

其他回答

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

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

你可能想要使用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()

你可以使用sort(), limit(),skip()从任何跳过的值开始获得最后N个记录

db.collections.find().sort(key:value).limit(int value).skip(some int value);