happy February 2016

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? Please help

Answers


ibininja February 2016

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.

To get the result in order use sort()

example:

db.collection.find({}).sort("_id":1)

Hope that helps


Daniel Figueroa February 2016

What happens is that mongodb generates an _id field for you. You can read more about it here: Create an Auto-Incrementing Sequence Field

and more specifically about ObjectId.

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.

Post Status

Asked in February 2016
Viewed 2,600 times
Voted 14
Answered 2 times

Search




Leave an answer