Answers:
这是对先前答案的重述,但更可能适用于不同的mongodb版本。
db.collection.find().limit(1).sort({$natural:-1})
db.collection.find().sort({$natural:-1}).limit(1).pretty()
Query failed with error code 303 and error message 'option $natural is not supported' on server docdb
。希望该功能即将推出。
这将为您提供最后一份文件 collection
db.collectionName.findOne({}, {sort:{$natural:-1}})
$natural:-1
表示与插入记录相反的顺序。
编辑:对于所有的拒绝投票者,上面是Mongoose语法,mongo CLI语法是:db.collectionName.find({}).sort({$natural:-1}).limit(1)
我需要一个具有恒定时间响应的查询
默认情况下,MongoDB中的索引是B树。搜索B树是O(logN)操作,因此甚至find({_id:...})
不会提供恒定的时间O(1)响应。
也就是说,_id
如果您使用的ObjectId
是ID ,也可以按进行排序。有关详细信息,请参见此处。当然,即使这样也只能持续到最后一秒。
您可以求助于“两次书写”。一次写入主集合,然后再次写入“最新更新”集合。如果没有交易,这将不是完美的,但是只有“上次更新”集合中的一项,它将总是很快。
从MongoDB集合中获取最后一个项目的另一种方法(不要介意示例):
> db.collection.find().sort({'_id':-1}).limit(1)
法线投影
> 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." }
排序投影(_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})
,根据所有文档的_id
s 降序定义投影。
排序投影(_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." }
我的解决方案:
db.collection("name of collection").find({}, {limit: 1}).sort({$natural: -1})
这是如何从“ 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 })
您可以在组中添加或删除
帮助文章:https : //docs.mongodb.com/manual/reference/operator/aggregation/group/#pipe._S_group
https://docs.mongodb.com/manual/reference/operator/aggregation/last/
db.collection.find().limit(1).sort({$natural:-1}).pretty()
如果您希望它看起来不错