Rohan Kumar Rohan Kumar - 1 year ago 113
PHP Question

How to create auto increment field

I want to add auto increment value in a field in mongodb using php, without using counting the records and next number(count + 1) will be my increment value...
Or Is there any way to create array of autoincrement values in

for example A customer having multiple emails and addresses then we can store it like
and also same for
So for uniqueness I want to set autoincrement value from each email and address..

Answer Source

It is possible if you create two collections

First to store the field for whichyou want to create autoincrement number like

// Inserting 2 records for which we want to create auto-increment numbers
   field_id: "register_id",
   nextId: 0
   field_id: "user_id",
   nextId: 0

// Function is used to get the next autoincremented value
function getNextId(field)
   var ret = db.autoincrementcollection.findAndModify({
        query: { field_id: field },
        update: { $inc: { nextId: 1 } },
        new: true
   return ret.nextId;

Second in which you want to use the incremented number like

// inserting data in registration collection with register_id auto-increment number
     _id: getNextId("register_id"),
     fname: "Rohan",
// inserting data in user collection with user_id auto-increment number
     _id: getNextId("user_id"),
     name: "Rohan Kumar"

findAndModify() may not work while code using PHP then you can use find() and/or update()

Refer Docs for create-an-auto-incrementing-field

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download