Skip to content

Instantly share code, notes, and snippets.

@DimDev
Created September 2, 2013 08:59
Show Gist options
  • Save DimDev/6410765 to your computer and use it in GitHub Desktop.
Save DimDev/6410765 to your computer and use it in GitHub Desktop.
Save documents into Mongodb collection with autoincrement field
<?php
/**
* @Author Dmitry Kazberovich
*/
class CustomMongoCollection extends MongoCollection
{
private $_autoincrementFieldName;
public function __construct($db, $collectionName, $autoincrementFieldName = '')
{
$this->_autoincrementFieldName = $autoincrementFieldName;
return parent::__construct($db, $collectionName);
}
public function insert($document, $options = array())
{
$document = (object) $document;
if (!empty($this->_autoincrementFieldName)) {
$this->saveWithAutoincrement($document, $options, 'insert');
} else {
return parent::insert($document, $options);
}
}
public function save($document, $options = array())
{
$document = (object) $document;
if (!empty($this->_autoincrementFieldName) && empty($document->{$this->_autoincrementFieldName})) {
$this->saveWithAutoincrement($document, $options, 'save');
} else {
return parent::save($document, $options);
}
}
protected function saveWithAutoincrement($document, $options, $operation = 'save')
{
while (1) {
$mongoCursor = $this->find(array(), array($this->_autoincrementFieldName))
->sort(array($this->_autoincrementFieldName => -1))
->limit(1);
if ($mongoCursor->hasNext()) {
$mongoCursor->next();
$doc = $mongoCursor->current();
$document->{$this->_autoincrementFieldName} = ++$doc[$this->_autoincrementFieldName];
} else {
$document->{$this->_autoincrementFieldName} = 1;
}
try {
return parent::$operation($document, $options);
} catch (MongoCursorException $e) {
if ($e->getCode() == '11000') //Duplicate key
{
continue;
} else {
throw $e;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment