Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrating from MySQL to MongoDB - auto increment field

Is there a way to guarantee a unique (auto-increment integer) field for MongoDB? I know you can do:

{ $inc : { field : value } }

But what if 2 queries hit at the same time? MySQL would insert one, then the other and both integers would be unique, but I don't actually know if Mongo does this or not.

Just to clarify, I know this isn't the ideal way to do it, but it's a temporary implementation until the data has finished migrating (user initiated) from MySQL.

like image 773
Roger Thomas Avatar asked Dec 10 '25 19:12

Roger Thomas


1 Answers

$inc is an atomic modifier, so yes, this will work. Make sure you use findAndModify so the find and modify are a single operation.

The problem is that $inc increments the value of a given document (row), which means you need to use a collection of counters, and apply the operation on that counter, then insert the actual document. I guess you know that, but felt it's worth to point it out to avoid confusion for readers who haven't read the docs on auto-incrementing fields.

like image 78
mnemosyn Avatar answered Dec 13 '25 09:12

mnemosyn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!