Search for the next document in MongoDb

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 am requesting product 1, is there any way to request the following document, which in this case will be product 2?

+6
source share
2 answers

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 () .

+12
source

You can return elements in insertion order using ObjectId. See: http://www.mongodb.org/display/DOCS/Optimizing+Object+IDs#OptimizingObjectIDs

If you want to return them in some other order, you will need to determine what the order is and store more information in your documents.

0
source

Source: https://habr.com/ru/post/923146/


All Articles