Is it bad to change _id type in MongoDB to integer

2019-01-11 13:20发布

问题:

MongoDB uses ObjectId type for _id.

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

(With this gem, if you're interested)

回答1:

No it isn't bad at all and in fact the built in OjbectId 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: http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/#auto-increment-counters-collection

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 have also got to consider the overhead of doing this yourself anyway, even without findAndModify. For every insert you have you will need to do an extra query. Image having a unique id that you have to query the uniqueness of every time you wanted to insert, eventually your insert rate will drop to a crawl and your lock 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.

That being said it is not the worst idea in the world and if you think it suites your scenario then go for it but bare in mind that if you don't require the auto incrementing id it could be a burden to you.



回答2:

You can do it, but you are responsible to make sure that the integers are unique.

MongoDB doesn't support auto-increment fields like most SQL databases. When you have a distributed or multithreaded application which has multiple processes and/or threads which create new database entries, you have to make sure that they use the same counter. Otherwise it could happen that two threads try to store a document with the same _id in the database.

When that happens, one of them will fail. That means you have to wait for the database to return a success or error (by calling GetLastError or by setting the write concerns to acknowledged), which takes longer than just sending data in a fire-and-forget manner.