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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4421207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 11:52:58  来源:igfitidea点击:

How to get the last N records in mongodb?

mongodbrecord

提问by Bin Chen

I can't find anywhere it has been documented this. By default, the find() operation will get the records from beginning. How can I get the last N records in mongodb?

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

Edit: also I want the returned result ordered from less recent to most recent, not the reverse.

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

回答by Justin Jenkins

If I understand your question, you need to sort in ascending order.

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

Assuming you have some id or date field called "x" you would do ...

假设您有一些名为“x”的 id 或日期字段,您会这样做......

.sort()

。种类()



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

The 1will sort ascending (oldest to newest) and -1will sort descending (newest to oldest.)

1将按升序排序(最旧到最新)和-1将降序排序(从最新到最旧的)。

If you use the auto created _idfield it has a date embedded in it ... so you can use that to order by ...

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

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

That will return back all your documents sorted from oldest to newest.

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

Natural Order

自然秩序



You can also use a Natural Ordermentioned above ...

您也可以使用上面提到的自然顺序......

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

Again, using 1or -1depending on the order you want.

同样,根据您想要的顺序使用1-1

Use .limit()

使用 .limit()



Lastly, it's good practice to add a limit when doing this sort of wide open query so you could do either ...

最后,在进行此类广泛开放查询时添加限制是一种很好的做法,因此您可以执行以下任一操作...

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

or

或者

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

回答by Trasplazio Garzuglio

The last Nadded records, from less recent to most recent, can be seen with this query:

最近添加的N条记录,从最近到最近,可以通过这个查询看到:

db.collection.find().skip(db.collection.count() - N)

If you want them in the reverse order:

如果您希望它们按相反的顺序:

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

If you install Mongo-Hackeryou can also use:

如果您安装Mongo-Hacker,您还可以使用:

db.collection.find().reverse().limit(N)

If you get tired of writing these commands all the time you can create custom functions in your ~/.mongorc.js. E.g.

如果你厌倦了一直写这些命令,你可以在 ~/.mongorc.js 中创建自定义函数。例如

function last(N) {
    return db.collection.find().skip(db.collection.count() - N);
}

then from a mongo shell just type last(N)

然后从 mongo shell 中输入 last(N)

回答by Ashwini

In order to get last N records you can execute below query:

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

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

if you want only one last record:

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

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

Note: In place of $natural you can use one of the columns from your collection.

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

回答by pkp

you can use sort(), limit(),skip()to get last N record start from any skipped value

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

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

回答by Steve Wilhelm

Look under Querying: Sorting and Natural Order, http://www.mongodb.org/display/DOCS/Sorting+and+Natural+Orderas well as sort() under Cursor Methods http://www.mongodb.org/display/DOCS/Advanced+Queries

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

回答by Marty Hirsch

You can't "skip" based on the size of the collection, because it will not take the query conditions into account.

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

The correct solution is to sort from the desired end-point, limit the size of the result set, then adjust the order of the results if necessary.

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

Here is an example, based on real-world code.

这是一个基于真实世界代码的示例。

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

回答by bello hargbola

You can try this method:

你可以试试这个方法:

Get the total number of records in the collection with

获取集合中的记录总数

db.dbcollection.count() 

Then use skip:

然后使用跳过:

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

回答by Jo?o Otero

Sorting, skipping and so on can be pretty slow depending on the size of your collection.

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

A better performance would be achieved if you have you collection indexed by some criteria; and then you could use min() cursor:

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

First, index you collection with db.collectionName.setIndex( yourIndex )You can use ascending or descending order, which is cool, because you want always the "N last items"... so if you index by descending order it is the same as getting the "first N items".

首先,索引你的集合db.collectionName.setIndex( yourIndex )你可以使用升序或降序,这很酷,因为你总是想要“N个最后项目”......所以如果你按降序索引它与获取“前N个项目”相同.

Then you find the first item of your collection and use its index field values as the min criteria in a search like:

然后,您找到集合的第一项,并使用其索引字段值作为搜索中的最小条件,例如:

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

Here's the reference for min() cursor: https://docs.mongodb.com/manual/reference/method/cursor.min/

这是 min() 游标的参考:https: //docs.mongodb.com/manual/reference/method/cursor.min/

回答by lauri108

@bin-chen,

@陈斌,

You can use an aggregation for the latest n entries of a subset of documents in a collection. Here's a simplified example without grouping (which you would be doing between stages 4 and 5 in this case).

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

This returns the latest 20 entries (based on a field called "timestamp"), sorted ascending. It then projects each documents _id, timestamp and whatever_field_you_want_to_show into the results.

这将返回最新的 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)
}

so, result would look something like:

所以,结果看起来像:

{ 
    "_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
}

Hope this helps.

希望这可以帮助。

回答by Lucbug

You may want to be using the findoptions : http://docs.meteor.com/api/collections.html#Mongo-Collection-find

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

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