Skip to content

Instantly share code, notes, and snippets.

@devoltt
Created March 11, 2019 10:23
Show Gist options
  • Select an option

  • Save devoltt/624b32e0fec139423786fc22a0db5140 to your computer and use it in GitHub Desktop.

Select an option

Save devoltt/624b32e0fec139423786fc22a0db5140 to your computer and use it in GitHub Desktop.
Add autoincrement id in mongodb documents
/**
* Add autoincrement id
*
* @return bool|int|mixed
*/
public function autoincrement(){
if (!$this->collectionName()) {
return false;
}
$collection = Yii::$app->mongodb->getCollection($this->collectionName());
$result = $collection->findOne([], ['id'], ['sort' => ['id' => -1]]);
$this->id = !isset($result) || !isset($result['id']) ? 1 : $result['id'] + 1;
return $this->id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment