function mongodb_next_id in MongoDB 6
Same name and namespace in other branches
- 7 mongodb.module \mongodb_next_id()
Return the next id in a sequence.
Parameters
string $name: The name of the sequence.
int $existing_id: The minimal value to be generated.
Return value
int The next id.
File
- ./
mongodb.module, line 295 - A library of common mechanisms for modules using MongoDB.
Code
function mongodb_next_id($name, $existing_id = 0) {
// Atomically get the next id in the sequence.
$mongo = mongodb();
$cmd = array(
'findandmodify' => mongodb_collection_name('sequence'),
'query' => array(
'_id' => $name,
),
'update' => array(
'$inc' => array(
'value' => 1,
),
),
'new' => TRUE,
);
// It's very likely that this is not necessary as command returns an array
// not an exception. The increment will, however, will fix the problem of
// the sequence not existing. Still, better safe than sorry.
try {
$sequence = $mongo
->command($cmd);
$value = isset($sequence['value']['value']) ? $sequence['value']['value'] : 0;
} catch (Exception $e) {
}
if (0 < $existing_id - $value + 1) {
$cmd = array(
'findandmodify' => mongodb_collection_name('sequence'),
'query' => array(
'_id' => $name,
),
'update' => array(
'$inc' => array(
'value' => $existing_id - $value + 1,
),
),
'upsert' => TRUE,
'new' => TRUE,
);
$sequence = $mongo
->command($cmd);
$value = isset($sequence['value']['value']) ? $sequence['value']['value'] : 0;
}
return $value;
}