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

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


当前回答

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

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

其他回答

使用$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();

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

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

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

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()

@bin-chen,

可以对集合中文档子集的最新n个条目使用聚合。下面是一个没有分组的简化示例(在本例中,您将在阶段4和阶段5之间进行分组)。

这将返回最新的20个条目(基于一个称为“时间戳”的字段),按升序排序。然后它将每个文档_id、时间戳和whatever_field_you_want_to_show投影到结果中。

var pipeline = [
        {
            "$match": { //stage 1: filter out a subset
                "first_field": "needs to have this value",
                "second_field": "needs to be this"
            }
        },
        {
            "$sort": { //stage 2: sort the remainder last-first
                "timestamp": -1
            }
        },
        {
            "$limit": 20 //stage 3: keep only 20 of the descending order subset
        },
        {
            "$sort": {
                "rt": 1 //stage 4: sort back to ascending order
            }
        },
        {
            "$project": { //stage 5: add any fields you want to show in your results
                "_id": 1,
                "timestamp" : 1,
                "whatever_field_you_want_to_show": 1
            }
        }
    ]

yourcollection.aggregate(pipeline, function resultCallBack(err, result) {
  // account for (err)
  // do something with (result)
}

因此,结果看起来像这样:

{ 
    "_id" : ObjectId("5ac5b878a1deg18asdafb060"),
    "timestamp" : "2018-04-05T05:47:37.045Z",
    "whatever_field_you_want_to_show" : -3.46000003814697
}
{ 
    "_id" : ObjectId("5ac5b878a1de1adsweafb05f"),
    "timestamp" : "2018-04-05T05:47:38.187Z",
    "whatever_field_you_want_to_show" : -4.13000011444092
}

希望这能有所帮助。