It is best to add explicit sort() criteria if you want a predictable order of results.
Assuming you order after that is the "insertion order" and you use ObjectIds created by default MongoDB, then you can query based on ObjectId:
// Find next product created db.products.find({_id: {$gt: ObjectId("4fdbaf608b446b0477000142") }}).limit(1)
Note that this example only works because:
- the first four bytes of ObjectId are computed using a unix-style timestamp (see ObjectId Specification )
- a request only on
_id will use the default _id index (sorted by id) to find a match
So this implicit view is the same as:
db.products.find({_id: {$gt: ObjectId("4fdbaf608b446b0477000142" )}}).sort({_id:1}).limit(1);
If you have added additional criteria for the query to find out how to find the βnextβ product (for example, category ), the query may use a different index, and the order may not be what you expect.
You can check the use of the index with explain () .
source share