Check if MongoDB upsert did an insert or an update

前端 未结 5 972
自闭症患者
自闭症患者 2020-12-03 09:26

I can\'t find this in the documentation in any of the obvious places. I\'d like to know if it is possible to know if Mongo executed an insert or update in the upsert operati

5条回答
  •  醉梦人生
    2020-12-03 10:14

    Using MongoDB driver 3.5.9 under Node.js, I found that there are these properties we are interested in after using updateOne with { upsert: true }:

    {
      modifiedCount: 0,
      upsertedId: null,
      upsertedCount: 0,
      matchedCount: 1
    }
    

    When upsert inserted something, we will get upsertedCount > 0 and upsertedId will hold the newly inserted document ID. When upsert modified something, we will get modifiedCount > 0.

    The tutorial for all CRUD operations is here https://mongodb.github.io/node-mongodb-native/3.6/tutorials/crud/

提交回复
热议问题