Home » Php » php – Finding The Next Document in MongoDb

php – Finding The Next Document in MongoDb

Posted by: admin July 12, 2020 Leave a comment


If this is my collection structure:

{   "_id": ObjectId("4fdbaf608b446b0477000142"),
    "name": "product 1",
{   "_id": ObjectId("fghfghfgjhjghkgk"),
    "name": "product 2",
{   "_id": ObjectId("fghfghfgjhjghkgk"),
    "name": "product 3",

and I query product 1, is there a way to query the next document, which in this case would be product 2?

How to&Answers:

It is best to add explicit sort() criteria if you want a predictable order of results.

Assuming the order you are after is “insertion order” and you are using MongoDB’s default generated ObjectIds, then you can query based on the 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 the ObjectId are calculated from a unix-style timestamp (see: ObjectId Specification)
  • a query on _id alone will use the default _id index (sorted by id) to find a match

So really, this implicit sort is the same as:

db.products.find({_id: {$gt: ObjectId("4fdbaf608b446b0477000142" )}}).sort({_id:1}).limit(1);

If you added more criteria to the query to qualify how to find the “next” product (for example, a category), the query could use a different index and the order may not be as you expect.

You can check index usage with explain().


You can get the items back in insertion order using ObjectId. See: http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs#OptimizingObjectIDs

If you want to get them back in some other order then you will have to define what that order is and store more information in your documents.