0

I need to fetch the document in a mongodb collection using its position. I know the position of the document inside the collection exactly but could not figure out a way to pull those documents from collection. Is there any way to achieve this?

db.daily.find({'_id': {'$in': 0,5,8}}) 

This is what i tried but _id is not inserted as 1,2,3... but it has some random num Eg:57d8fd62f2a9d913ba0d006d. Thanks in advance.

Sai
  • 15,188
  • 20
  • 81
  • 121

1 Answers1

1

You can use skip and limit to query based on the position in the natural order

db.collection.find().skip(10).limit(1) // get 10th document in natural order

As the natural order link points out, the document order need not match the order that documents are inserted (with an exception for capped collections). If you use the default ObjectId as the _id field for your documents you can sort by _id to order based on insertion in the collection (up to the resolution of the timestamp in the ObjectId)

db.collection.find().sort([("_id",1)]).skip(10).limit(1) // get 10th document in inserted order

You may also consider using your own _id or adding a field to be able to sort on in order to query based on the position you define.

Community
  • 1
  • 1
logan rakai
  • 2,519
  • 2
  • 15
  • 24
  • Nice thanks, is there any way to get multiple documents in one query considering i have multiple positions ? – Sai Sep 17 '16 at 06:30
  • when i try this ` for i in range(0, 2): horolist.append(db.daily.find().sort({"_id": 1}).skip(i).limit(1)) ` i got an exception saying `TypeError: if no direction is specified, key_or_list must be an instance of list` – Sai Sep 17 '16 at 06:54
  • If they are contiguous you can use `limit(N)` to get N in a row. Otherwise you should consider adding a position field and using `$in` or multi-range query on the field – logan rakai Sep 17 '16 at 06:56
  • I was giving mongo shell/js syntax. For python you will need to use a list for `.sort([("_id", 1)])` http://stackoverflow.com/a/10242305/5894196 (updated answer to use python syntax) – logan rakai Sep 17 '16 at 06:59
  • Thank you.. It helped a lot http://stackoverflow.com/questions/5125521/uses-for-mongodb-objectid-creation-time . – Sai Sep 17 '16 at 07:02