Increment of records at the same time

  • 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;
return $company->nfe_numero_seq_atual;

/* Test using the increment */
$company = self::find($this->_id);
$company->increment(‘nfe_numero_seq_atual’, 1);
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.

Hello @Kleber_Marioti
Welcome to the Community Forum!! :star_struck:

There are a few things which I would like to understand from the above post:

  1. Are you making two requests concurrently to increment the same variable?
  2. According to the function:

The nfe_numero_seq_atual gets incremented only once and hence one update operation is performed.

Can you please help me understand, the two updates you are trying to perform.

Also, please refer to the documentation for findOneAndUpdate to use the operator for the scenario mentioned.

Please help us with the above questions so that we could help you better.