Is it bad to change _id type in MongoDB to integer?

just so picture just so · Dec 27, 2012 · Viewed 20k times · Source

MongoDB uses ObjectId type for _id.

Will it be bad if I make _id an incrementing integer?

(With this gem, if you're interested)

Answer

Sammaye picture Sammaye · Dec 27, 2012

No it isn't bad at all and in fact the built in ObjectId is quite sizeable within the index so if you believe you have something better then you are more than welcome to change the default value of the _id field to whatever.

But, and this is a big but, there are some considerations when deciding to move away from the default formulated ObjectId, especially when using the auto incrementing _ids as shown here: https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field

Multi threading isn't such a big problem because findAndModify and the atomic locks can actually take care of that, but then you just hit into your first problem. findAndModify is not the fastest function nor the lightest and there have been significant performance drops noticed when using it regularly.

You also have to consider the overhead of doing this yourself anyway, even without findAndModify. For every insert you will need an extra query. Imagine having a unique id that you have to query the uniqueness of every time you want to insert. Eventually your insert rate will drop to a crawl and your lock time will build up.

Of course the ObjectId is really good at being unique without having to check or formulate its own uniqueness by touching the database prior to insertion, hence it doesn't have this overhead.

If you still feel an integer _id suites your scenario, then go for it, but bare in mind the overhead described above.