Document return range around identifier in MongoDB

I have a document identifier and you need to return the document, as well as 10 documents that were submitted earlier, and 10 documents after it. A total of 21 documents.

I have no start or end value from any key. Only the limit in any direction.

Best way to do this? Thank you in advance.

+6
source share
2 answers

Do you know that ObjectID contains a timestamp? And so they always represent the natural insertion order. Therefore, if you are looking for documents before after the famous _id document, you can do this:

Our documents:

 { "_id" : ObjectId("5307f2d80f936e03d1a1d1c8"), "a" : 1 } { "_id" : ObjectId("5307f2db0f936e03d1a1d1c9"), "b" : 1 } { "_id" : ObjectId("5307f2de0f936e03d1a1d1ca"), "c" : 1 } { "_id" : ObjectId("5307f2e20f936e03d1a1d1cb"), "d" : 1 } { "_id" : ObjectId("5307f2e50f936e03d1a1d1cc"), "e" : 1 } { "_id" : ObjectId("5307f2e90f936e03d1a1d1cd"), "f" : 1 } { "_id" : ObjectId("5307f2ec0f936e03d1a1d1ce"), "g" : 1 } { "_id" : ObjectId("5307f2ee0f936e03d1a1d1cf"), "h" : 1 } { "_id" : ObjectId("5307f2f10f936e03d1a1d1d0"), "i" : 1 } { "_id" : ObjectId("5307f2f50f936e03d1a1d1d1"), "j" : 1 } { "_id" : ObjectId("5307f3020f936e03d1a1d1d2"), "j" : 1 } 

So, we know _id from "f", we get it and the following 2 documents:

 > db.items.find({ _id: {$gte: ObjectId("5307f2e90f936e03d1a1d1cd") } }).limit(3) { "_id" : ObjectId("5307f2e90f936e03d1a1d1cd"), "f" : 1 } { "_id" : ObjectId("5307f2ec0f936e03d1a1d1ce"), "g" : 1 } { "_id" : ObjectId("5307f2ee0f936e03d1a1d1cf"), "h" : 1 } 

And do the same in reverse order:

 > db.items.find({ _id: {$lte: ObjectId("5307f2e90f936e03d1a1d1cd") } }) .sort({ _id: -1 }).limit(3) { "_id" : ObjectId("5307f2e90f936e03d1a1d1cd"), "f" : 1 } { "_id" : ObjectId("5307f2e50f936e03d1a1d1cc"), "e" : 1 } { "_id" : ObjectId("5307f2e20f936e03d1a1d1cb"), "d" : 1 } 

And this is a much better approach than scanning a collection.

+5
source

Neil's answer is a good answer to the question as indicated (if you use automatically created ObjectIds), but keep in mind that there is some subtlety around the concept of 10 documents before and after this document.

The full format for ObjectId is documented here . Please note that it consists of the following fields:

  • time stamp with a resolution of 1 second,
  • machine id
  • process id
  • Counter

Usually, if you do not specify your own _ids, they are automatically generated by the driver on the client machine. Thus, while ObjectIds are generated on a single process on a client-side machine, their order does reflect the order in which they were generated, which in a typical application will also have an insertion order (but not required). However, if you have multiple processes or multiple client machines, the order of the ObjectIds for the objects generated by these several sources within a given second has an unpredictable relation to the insertion order.

+1
source

All Articles