How to use $inc, $min and $setOnInsert in an update operation in MongoDB?

Viewed 295

I want to perform an operation like this in MongoDB:

Find the data through the query {"name": "A.C. Abracus"}. If the data doesn't exist, it will create the data in the database by using $setOnInsert. If the data exists, it will increase the cmtCount by 1, and in the meantime compares the new point value with the existing point in the database in order to choose the min one of them and update the point field with the min value.

The data in the MongoDB is like this below:

>db.scores.find() { "_id" : ObjectId("5d08a9c83bb571704b774a60"), "name" : "A.C. Abracus", "assignment" : 5, "cmtcount" : 1, "point" : 33 }

I have tried some operations like findOneAndUpdate and update with $set, $setOnInsert, $inc, $min, but doesn't work as my expectation. Like:

db.scores.update(
  {"name": "A.C. Abracus"},
  {
    $min: {"point": 10},
    $inc: {"cmtcount": 1},
    $setOnInsert: {"name": "A.C. Abracus", "assignment": 5, "point": 33}
  },
  {upsert: true}
)

I expect the result to be like this: { "_id" : ObjectId("5d08a9c83bb571704b774a60"), "name" : "A.C. Abracus", "assignment" : 5, "cmtcount" : 2, "point" : 10 }

But this occured an error "Updating the path 'point' would create a conflict at 'point'"

I think maybe it is because when the data doesn't exist, it runs $setOnInsert, $min and $inc at the same time. So it occurs conflict.

How can I solve this problem? Thanks!

0 Answers
Related