How to set primary key with auto increment in MongoDB ?
Normally MongoDB generates ObjectID. I wanna use my own auto increment primary key like MySQL.
Examples would be appreciated :)
MongoDB does not have out-of-the-box auto-increment functionality, like SQL databases. By default, it uses the 12-byte ObjectId for the _id field as the primary key to uniquely identify the documents.
Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
_id field is reserved for primary key in mongodb, and that should be a unique value. If you don't set anything to _id it will automatically fill it with "MongoDB Id Object". But you can put any unique info into that field.
Benefits. ObjectID is automatically generated by the database drivers, and will be assigned to the _id field of each document.
I blogged about this here:
http://www.alexjamesbrown.com/blog/development/mongodb-incremental-ids/
I also started a int id generator for the C# driver:
https://github.com/alexjamesbrown/MongDBIntIdGenerator
However, incrementing ID's won't scale effectively.
$db->execute("return db.getCollection('autoInccollection').findAndModify({
query: { collection: '$colle' },
update: { '$inc': { primaryKey: 1 } },new: true
})");
$colle means which collection you need to create the Auto increment key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With