Can findOne match first or last?

后端 未结 2 462
忘了有多久
忘了有多久 2021-01-23 04:06

I\'m specifically using mongoose, although I don\'t believe that matters that much. For example, say I have a collection called MongoQueue and I add a few people to that queue.<

2条回答
  •  有刺的猬
    2021-01-23 05:00

    The findOne() function returns documents in the natural order, which is the order on disk. You cannot count on this returning the least recently inserted document. To return the least recently inserted document, you can use the find() function with an inverse sort on _id and a limit of 1, assuming _id is a default ObjectId generated for you, or on a timestamp (_id is built, in part, from a timestamp, which is why it works with _id). If you use _id (which is always indexed) or index the timestamp field, this will be very fast.

提交回复
热议问题