Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

Using findOne in mongodb to get element with max 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...