Check if MongoDB upsert did an insert or an update

For reference only, in node.js:

collection.update( source, target, { upsert: true }, function(err, result, upserted) {
  ...
});

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

Tags:

Mongodb