MongoDB’s db.collection.find().limit(10000) does NOT return the first 10000 documents I inserted. How would I make MongoDB return documents in the order they were inserted?
MongoDB’s db.collection.find().limit(10000) does NOT return the first 10000 documents I inserted. How would I make MongoDB return documents in the order they were inserted?
2
Answers
You can sort items by _id field.
id field is auto-increment and you can sort item in asc or desc to get last or first of you collection.
Mongodb sorts document based on a natual order. However, as you have found out, it is not 100% reliable. Documents grow and move internally.
Since you have 10s of millions of rows you face the problem of having to use
.find()
which will select all documents, then sort them, then limit to 10000. Not great for performance, I agree.Mongodb has a $natural operator that you can use to sort results in their natural order (on disk) but best practice is to create a view and use it that way.
You could try this and check for performance:
Note the use of
{_id: {$ne : null}}
. This forces$natural
to use indexes to fulfil the query (speed things up).Disclaimer:
However, I would think sorting by
_id
would result in better insertion ordering. That’s becuase if your_id
field is anObjectId
then:So the 4-byte value representing the seconds since the Unix epoch will always be incremental. Try this way:
You could then do this to get the next 10000: