Rohan Kumar
Rohan Kumar

Reputation: 40639

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:'[email protected]',2:'[email protected]'},...] and also same for address[{1:'Indore',2:'Dewas'},...] So for uniqueness I want to set autoincrement value from each email and address..

Upvotes: 1

Views: 7864

Answers (4)

kunal
kunal

Reputation: 11

It is possible we have to get max id form collection

db -> collection -> find() -> sort(array('id' => -1)) -> limit(1) 

It return max id array. Add db['id'] + 1;

Every time need not store the auto-increment id in mongo

Upvotes: 1

Payam Khaninejad
Payam Khaninejad

Reputation: 7996

This is my method for creating auto increment id in MongoDB PHP library:

private function get_last_id()
    {
        // put your connection string blow
        $client = new MongoDB\Client('');
        $counterCollection = $client->collection->counter;
        $counter["id"]=1;
        if ($counterCollection->count()<=0) {
            $insertOneResult = $counterCollection->insertOne($counter);
        } else {
            $filter  = [];
            $options = ['sort' => ['_id' => -1], 'limit' => 1];
            $doc = $counterCollection->findOne($filter, $options);
            $id=$doc->id+1;
            $updateResult = $counterCollection->updateOne(
            [ '_id' => $doc->_id ],
            [ '$set' => [ 'id' =>$id ]]
        );
            return $id;
        }
    }

Upvotes: 0

Rohan Kumar
Rohan Kumar

Reputation: 40639

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

Upvotes: 2

DhruvPathak
DhruvPathak

Reputation: 43255

Ideally you should not be using autoincrement as identifier in MongoDb. If you want to , refer 2 good methods given here :

http://www.mongodb.org/display/DOCS/How+to+Make+an+Auto+Incrementing+Field

Upvotes: 0

Related Questions