mongodb 从mongodb集合中获取最新记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10920651/
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
Get the latest record from mongodb collection
提问by inkriti
I want to know the most recent record in a collection. How to do that?
我想知道集合中的最新记录。怎么做?
Note: I know the following command line queries works:
注意:我知道以下命令行查询有效:
1. db.test.find().sort({"idate":-1}).limit(1).forEach(printjson);
2. db.test.find().skip(db.test.count()-1).forEach(printjson)
where idate has the timestamp added.
其中 idate 添加了时间戳。
The problem is longer the collection is the time to get back the data and my 'test' collection is really really huge. I need a query with constant time response.
问题是收集时间更长,取回数据,而我的“测试”收集真的非常庞大。我需要一个具有恒定时间响应的查询。
If there is any better mongodb command line query, do let me know.
如果有更好的 mongodb 命令行查询,请告诉我。
回答by Digits
This is a rehash of the previous answer but it's more likely to work on different mongodb versions.
这是对先前答案的重新整理,但它更有可能适用于不同的 mongodb 版本。
db.collection.find().limit(1).sort({$natural:-1})
回答by dark_ruby
This will give you one last document for a collection
这将为您提供最后一份文件 collection
db.collectionName.findOne({}, {sort:{$natural:-1}})
$natural:-1
means order opposite of the one that records are inserted in.
$natural:-1
表示与插入记录的顺序相反的顺序。
Edit: For all the downvoters, above is a Mongoose syntax,
mongo CLI syntax is: db.collectionName.find({}).sort({$natural:-1}).limit(1)
编辑:对于所有downvoters,上面是Mongoose语法,mongo CLI语法是:db.collectionName.find({}).sort({$natural:-1}).limit(1)
回答by Gates VP
I need a query with constant time response
我需要一个具有恒定时间响应的查询
By default, the indexes in MongoDB are B-Trees. Searching a B-Tree is a O(logN) operation, so even find({_id:...})
will not provide constant time, O(1) responses.
默认情况下,MongoDB 中的索引是 B 树。搜索 B 树是一个 O(logN) 操作,因此即使find({_id:...})
不会提供恒定时间,O(1) 响应。
That stated, you can also sort by the _id
if you are using ObjectId
for you IDs. See here for details. Of course, even that is only good to the last second.
也就是说,您还可以按_id
是否ObjectId
用于 ID 进行排序。有关详细信息,请参见此处。当然,即使那样也只好到最后一秒。
You may to resort to "writing twice". Write once to the main collection and write again to a "last updated" collection. Without transactions this will not be perfect, but with only one item in the "last updated" collection it will always be fast.
你可能会诉诸于“写两次”。一次写入主集合并再次写入“上次更新”集合。如果没有事务,这将不是完美的,但是在“上次更新”集合中只有一个项目时,它总是很快。
回答by ivanleoncz
Yet another way of getting the last item from a MongoDB Collection (don't mind about the examples):
从 MongoDB 集合中获取最后一项的另一种方法(不要介意示例):
> db.collection.find().sort({'_id':-1}).limit(1)
Normal Projection
正常投影
> db.Sports.find()
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2017", "Body" : "Again, the Pats won the Super Bowl." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
Sorted Projection ( _id: reverse order )
排序投影(_id:逆序)
> db.Sports.find().sort({'_id':-1})
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2018", "Body" : "Again, the Pats won the Super Bowl" }
sort({'_id':-1})
, defines a projection in descending order of all documents, based on their _id
s.
sort({'_id':-1})
, 定义所有文档的降序投影,基于它们的_id
s。
Sorted Projection ( _id: reverse order ):getting the latest (last) document from a collection.
排序投影(_id:逆序):从集合中获取最新(最后)文档。
> db.Sports.find().sort({'_id':-1}).limit(1)
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
回答by Sam
php7.1 mongoDB:$data = $collection->findOne([],['sort' => ['_id' => -1],'projection' => ['_id' => 1]]);
php7.1 MongoDB:$data = $collection->findOne([],['sort' => ['_id' => -1],'projection' => ['_id' => 1]]);
回答by Abdul Alim Shakir
My Solution :
我的解决方案:
db.collection("name of collection").find({}, {limit: 1}).sort({$natural: -1})
db.collection("name of collection").find({}, {limit: 1}).sort({$natural: -1})
回答by Chan15
If you are using auto-generated Mongo Object Ids in your document, it contains timestamp in it as first 4 bytes using which latest doc inserted into the collection could be found out. I understand this is an old question, but if someone is still ending up here looking for one more alternative.
如果您在文档中使用自动生成的 Mongo 对象 ID,它会在其中包含时间戳作为前 4 个字节,使用可以找到插入到集合中的最新文档。我知道这是一个老问题,但如果有人仍然在这里寻找更多选择。
db.collectionName.aggregate(
[{$group: {_id: null, latestDocId: { $max: "$_id"}}}, {$project: {_id: 0, latestDocId: 1}}])
Above query would give the _idfor the latest doc inserted into the collection
上面的查询将给出插入到集合中的最新文档的_id
回答by ssymbiotik
This is how to get the lastrecord from all MongoDB documents from the "foo" collection.(change foo,x,y.. etc.)
这是如何从“foo”集合中的所有 MongoDB 文档中获取最后一条记录。(更改 foo,x,y.. 等)
db.foo.aggregate([{$sort:{ x : 1, date : 1 } },{$group: { _id: "$x" ,y: {$last:"$y"},yz: {$last:"$yz"},date: { $last : "$date" }}} ],{ allowDiskUse:true })
you can add or remove from the group
您可以从组中添加或删除
help articles: https://docs.mongodb.com/manual/reference/operator/aggregation/group/#pipe._S_group
帮助文章:https: //docs.mongodb.com/manual/reference/operator/aggregation/group/#pipe._S_group
https://docs.mongodb.com/manual/reference/operator/aggregation/last/
https://docs.mongodb.com/manual/reference/operator/aggregation/last/