我正在尝试从一个mongo集合中检索一个元素,一个元素最大的是_id字段。 我知道这可以通过查询来完成:
db.collection.find().sort({_id: -1}).limit(1)但是,这似乎是不切实际的,我想知道是否有办法使用findOne()获取特定的元素
注意:我想这样做,因为从我在ObjectId中读取的内容,第一个字节对应于从Epoch开始的毫秒数,因此插入的最后一个元素将具有最大的_id。 有没有其他方法来检索插入到集合中的最后一个元素?
I am trying to retrieve one element from a mongo collection, the one with the greatest _id field. I know this can be done by querying:
db.collection.find().sort({_id: -1}).limit(1)But it kind of seems unelegant and I was wondering whether there is a way to get that specific element using findOne()
Note: I want to do this because, from what I've read in ObjectId, the first bytes correspond to the miliseconds since the Epoch and thus, the last element being inserted will have the greatest _id. Is there any other way to retrieve the last element inserted in a collection?
最满意答案
你应该使用find ,就像你已经是,而不是汇总,因为它需要扫描_id字段的所有值,以找出最大值。
正如评论指出的那样,使用find()和findOne()在功能上或优雅方面没有区别。 事实上,shell中的findOne (以及实现它的驱动程序)是根据find(限制为-1,在shell中打印的)定义的。
如果你真的想做相当的
db.collection.find().sort({_id:-1}).limit(1).pretty()作为findOne您可以使用以下语法:
db.collection.findOne({$query:{},$orderby:{_id:-1}})You should use find, like you already are, and not aggregation which will be slower since it needs to scan all the values of _id fields to figure out the max.
As comments pointed out there is no difference between using find() and findOne() - functionally or elegance-wise. In fact, findOne in the shell (and in the drivers which implement it) is defined in terms of find (with limit -1 and with pretty print in the shell).
If you really want to do the equivalent of
db.collection.find().sort({_id:-1}).limit(1).pretty()as findOne you can do it with this syntax:
db.collection.findOne({$query:{},$orderby:{_id:-1}})更多推荐
发布评论