kgneng2 / blokg

blog
MIT License
0 stars 0 forks source link

mongodb findOneAndUpdate duplicate issues #58

Open kgneng2 opened 2 years ago

kgneng2 commented 2 years ago

이슈

....findOneAndUpdate(
       {
          nidNo,
        },
        {
          $set: {
            updatedDate: new Date(),
            grade: SMART
          },
        },
        {
          upsert: true,
        },
      );

위와 같은 쿼리 날렸을 때, nidNo에 대해서 중복된 데이터가 들어갈때가 있다.

reference

https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/#std-label-upsert-and-unique-index

When using the upsert: true option with the findOneAndUpdate() method, and not using a unique index on the query field(s), multiple instances of a findOneAndUpdate() operation with similar query field(s) could result in duplicate documents being inserted in certain circumstances.

To ensure that only one such document is created, and the other findOneAndUpdate() operations update this new document instead, create a unique index on the name field. This guarantees that only one document with name: Andy is permitted in the collection.

With this unique index in place, the multiple findOneAndUpdate() operations now exhibit the following behavior:

Exactly one findOneAndUpdate() operation will successfully insert a new document. All other findOneAndUpdate() operations will update the newly-inserted document, incrementing the score value.

create unique index

db.collection.createIndex({nidNo:1}, {unique:true})