There is an application written on node expressjs, the base is used by mongodb.

The algorithm is as follows: when the post comes in, a record is searched for in the fields name , server , fraction . If there is such an entry, update, if not, create one.

The problem is that with a large number of requests, if it does not find a record, it creates not one record, but several. I assume that while mongodb creates a record, the next search does not give results, because the record has not yet been created and the search does not give results, and mongodb creates another identical record, although it has to update.

How to solve this problem?

  • 2
    Did not deal with mongoDB, but, offhand, a cursory search on the documentation led to the method insertOne (or insertMany ) with the parameter upsert: true . Judging by the description, it does the same thing as described in the question ( "Если такая запись есть то обновить, если нет то создать." ), But not by means of an external code, but by the base itself. It is more than likely that in this case duplicates will not be created. Let knowledgeable people confirm or deny. :) - Yaant
  • You can refer to the documentation for the method inserOne. - darut
  • one
    docs.mongodb.com/manual/reference/method/db.collection.update update (update) with the flag upsert, this is what you need, if there is no document, it will be created. - Vladimir Gamalyan
  • In, knowledgeable people correctly say, the update also has a flag upsert , to this my quick search did not bring me. :) So you need the update . :) - Yaant

0