- Laravel: 9
- Laravel-mongodb Version: 3.9
- PHP Version: 8.1
- MongoDB extension version: 1.12.0
- Edition: MongoDB 5.0.6 Enterprise
Hello, how are you? I’m using the following method
public function getNfeNumeroNext() { $this->nfe_numero_seq_atual = $this->nfe_numero_seq_atual + 1; $this->save(); return $this->nfe_numero_seq_atual; }
The method identifies the current number and increments it by 1.
However, when two processes are performed at the same time, minute and second, the same number is saved in both requests, because mongo is not able to perform two updates at the same time. I’ve already tried using the following solutions:
/* Test using lockForUpdate or sharedLock */
$company = self::lockForUpdate()->find($this->_id);
$company = self::sharedLock()->find($this->_id);
$company->nfe_numero_seq_atual = $company->nfe_numero_seq_atual + 1;
$company->save();
return $company->nfe_numero_seq_atual;
/* Test using the increment */
$company = self::find($this->_id);
$company->increment(‘nfe_numero_seq_atual’, 1);
$company->save();
return $company->nfe_numero_seq_atual;
/* Test using the collection and increment */
$update_company = DB::collection(‘companies’)->where(’_id’, $this->_id)->increment(‘nfe_numero_seq_atual’, 1);
$company = DB::collection(‘companies’)->find($this->_id);
return $company[‘nfe_numero_seq_atual’];`
Any solution to the problem described? Thank you for your attention, see you later.