Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set primary key with auto increment in MongoDB? [duplicate]

Tags:

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 :)

like image 900
Venks Avatar asked Aug 20 '13 11:08

Venks


People also ask

How do I auto increment a field in MongoDB?

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.

Can auto increment be a primary key?

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.

Can you set primary key in MongoDB?

_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.

Is MongoDB ID auto generated?

Benefits. ObjectID is automatically generated by the database drivers, and will be assigned to the _id field of each document.


2 Answers

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.

like image 101
Alex Avatar answered Sep 20 '22 17:09

Alex


$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.

like image 24
Sanith Avatar answered Sep 22 '22 17:09

Sanith