Mongodb documents are not arranged in proper order
When i manually insert 5 rows into mongodb database i can see the id field in increasing order but when I insert 6th row which has greater id no comes first when i query the collection. how to insert in increasing order of id field?
You will have to do that when obtaining the data from mongodb. MongoDB does natural insert it does not preserve the order on insertion (It does for fields inside documents but not the documents it self.).
Update: I have not tried this but there is ordered operator you can use on insertion to preserve order.
But actually the only constraint on _id is that it is unique, so you could roll out your own sequential implementation, but that is not recommended.
Generally in MongoDB, you would not use an auto-increment pattern for the _id field, or any field, because it does not scale for databases with large numbers of documents. Typically the default value ObjectId is more ideal for the _id.
If you're sure about you being the only one inserting values into the database, you could always get the timestamp from the ObjectId to view some sort of increment-feeling.
However if you only want to retrieve the values in the inserted order I suggest you do as @ibininja suggests.
Asked in February 2016Viewed 2,600 timesVoted 14Answered 2 times