在mongodb中使用findOne获取最大id的元素(Using findOne in mongodb to get element with max id)

系统教程 行业动态 更新时间:2024-06-14 16:57:18
在mongodb中使用findOne获取最大id的元素(Using findOne in mongodb to get element with max id)

我正在尝试从一个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}})

更多推荐

本文发布于:2023-04-12 20:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/2a499bed27c01017042da206bcda1ecb.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   findOne   mongodb   id   max

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!