如何获取mongodb中的最后N条记录?

我找不到任何记录在案的文件。 默认情况下,find()操作将从头开始获取记录。 如何获取mongodb中的最后N条记录?

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


#1楼

您可以使用sort()limit()skip()从任何跳过的值开始获取最后N条记录

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

#2楼

可以从此查询中看到最近添加的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)


#3楼

为了获得最后的N条记录,您可以执行以下查询:

db.yourcollectionname.find({$query: {}, $orderby: {$natural : -1}}).limit(yournumber)

如果您只想要最后一条记录:

db.yourcollectionname.findOne({$query: {}, $orderby: {$natural : -1}})

注意:您可以使用集合中的其中一列来代替$ natural。


#4楼

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

例:

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

#5楼

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

正确的解决方案是从所需的端点进行排序,限制结果集的大小,然后根据需要调整结果的顺序。

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

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

#6楼

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


#7楼

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

假设您有一些名为“ x”的id或日期字段,则可以...

。分类()


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

要么

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

#8楼

您可能希望使用find选项: http : //docs.meteor.com/api/collections.html#Mongo-Collection-find

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

#9楼

@ bin-chen,

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

这将返回最新的20个条目(基于称为“时间戳记”的字段),并按升序排序。 然后,它将每个文档_id,时间戳和what_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
}

希望这可以帮助。


#10楼

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

根据mongoDB文档

您可以指定{$ natural:1}强制查询执行前向集合扫描。

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


#11楼

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

地理位置是数据数组,从中我们得到最后5条记录。


#12楼

排序,跳过等操作可能会非常慢,具体取决于集合的大小。

如果按某些条件对集合进行索引,则可以实现更好的性能。 然后可以使用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/


#13楼

您可以尝试以下方法:

使用以下命令获取集合中的记录总数

db.dbcollection.count() 

然后使用跳过:

db.dbcollection.find().skip(db.dbcollection.count() - 1).pretty()
发布了0 篇原创文章 · 获赞 2 · 访问量 5925

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/104060658