Skip to content

Instantly share code, notes, and snippets.

@debojitkakoti
Last active October 27, 2020 06:31
Show Gist options
  • Save debojitkakoti/9565409 to your computer and use it in GitHub Desktop.
Save debojitkakoti/9565409 to your computer and use it in GitHub Desktop.
Auto Incrementing Sequence in mongodb using php mongo
<?php
$m = new MongoClient();
// select a database
$db = $m->seq;
// select a collection (analogous to a relational database's table)
$collection = $db->counters;
$user_collection = $db->user;
/******************Function to auto increment seq******************/
function getNextSequence($name){
global $collection;
$retval = $collection->findAndModify(
array('_id' => $name),
array('$inc' => array("seq" => 1)),
null,
array(
"new" => true,
)
);
return $retval['seq'];
}
/********************Example Usage**********************************/
$db_array=array('_id' => getNextSequence("userid"), 'name' => 'debojit');
$user_collection->insert($db_array);
@forzamilan
Copy link

try to add
"upsert" => true,
at line 22 - it will create needed rows in autoincrement collection if they are missing

@preethishekar26
Copy link

how to make it work if we are using mongodb driver

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment