[英]Get last document in MongoDB collection
I am trying to get the last document in a MongoDB collection.我正在尝试获取 MongoDB 集合中的最后一个文档。 The following works in the Mongo shell:
Mongo shell 中的以下工作:
db.collection.find().limit(1).sort({$natural:-1})
Results in the last object like so:最后一个 object 的结果如下:
{ "_id" : ObjectId("62c8817075c9400469b1fc3a"), "token" : "135e53ebb05aa2b6055513843cb8e0dca1", "createdAt" : ISODate("2022-07-08T19:11:44.730Z"), "updatedAt" : ISODate("2022-07-08T19:11:44.730Z"), "__v" : 0 }
But this does not work in my Express app:但这在我的 Express 应用程序中不起作用:
const last = FM_Model.find().limit(1).sort({$natural:-1})
console.log('Last Token from MONGODB here -> ', last)
In the code above the console.log returns a very long object related to the collection itself, but not the document I want.在上面的代码中,console.log 返回一个很长的 object 与集合本身相关,但不是我想要的文档。
I have tried other variations but nothing has worked so far.我尝试了其他变体,但到目前为止没有任何效果。 If anyone can give me any ideas of what I am missing that would be great.
如果有人可以给我任何关于我所缺少的东西的想法,那就太好了。
.find()
returns an array. .find()
返回一个数组。 But there is an better version with .findOne
wich return the result or undefined
但是
.findOne
有一个更好的版本,它返回结果或undefined
FM_Model.findOne({}, {}, { sort: { 'createdAt' : -1 } })
With -1
you get the oldest element, wich is the latest.使用
-1
,您将获得最旧的元素,这是最新的。
Try尝试
db.collection.find().sort({'_id':-1}).limit(1) db.collection.find().sort({'_id':-1}).limit(1)
First revert the order then get the first one首先恢复订单然后得到第一个
I would recommend sorting on the _id field as it's indexed by default: reference .我建议对 _id 字段进行排序,因为它是默认索引的: reference 。 Or you could sort by the createdAt if the field has a descending order index.
或者,如果字段具有降序索引,您可以按 createdAt 排序。
const last = await FM_Model.findOne({}).sort({ _id: -1 });
More about MongoDB indexing can be found here更多关于 MongoDB 索引的信息可以在这里找到
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.