Check if MongoDB upsert did an insert or an update

前端 未结 5 979
自闭症患者
自闭症患者 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:15

    Yes there is, on a safe call (or getLastError) the update function will return an array with an upsert field and a updatedExisting field.

    You can read the PHP version of this here: http://php.net/manual/en/mongocollection.insert.php towards the bottom.

    As it says within the documentation on upserted:

    If an upsert occured, this field will contain the new record's _id field. For upserts, either this field or updatedExisting will be present (unless an error occurred).

    So upserted contains the _id of the new record if a insert was done or it will increment updatedExisting if it updated a record.

    I am sure a similar thing appears in all drivers.

    Edit

    It will actually be a boolean in the updatedExisting field of true or false

提交回复
热议问题