Rohan Kumar Rohan Kumar - 3 months ago 13
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

mongodb
,
php
for example A customer having multiple emails and addresses then we can store it like
email[{1:'a@x.com',2:'demo@example.com'},...]
and also same for
address[{1:'Indore',2:'Dewas'},...]
So for uniqueness I want to set autoincrement value from each email and address..

Answer

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
db.autoincrementcollection.insert({
   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
db.registration.insert({
     _id: getNextId("register_id"),
     fname: "Rohan",
     lname:"Kumar"
});
// inserting data in user collection with user_id auto-increment number
db.users.insert({
     _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