Check if you were able to add MongoDB insert or update

I cannot find this in the documentation in any of the obvious places. I would like to know if it is possible to find out if Mongo performed an insert or update in an upsert operation?

+52
mongodb
Dec 19 '12 at 15:05
source share
4 answers

Yes, with a safe call (or getLastError), the update function will return an array with an upsert field and an updated Existing field.

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

As the upserted documentation upserted :

If recreation has occurred, this field will contain the new _id record field. For upserts, either this field or updateExisting will be present (if no error occurred).

So, upserted contains the _id new record if the insert was inserted or it will increase updatedExisting if it updates the record.

I am sure that a similar thing appears in all drivers.

Edit

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

+32
Dec 19 '12 at 15:12
source share

For reference only, in node.js:

 collection.update( source, target, { upsert: true }, function(err, result, upserted) { ... }); 
+11
Dec 19 '12 at 15:33
source share

For reference only, in node.js using Mongoose 3.6:

 model.update( findquery, updatequery, { upsert: true }, function(err, numberAffected, rawResponse) { ... }); 

If rawResponse looks like this when it updated an existing document:

 { updatedExisting: true, n: 1, connectionId: 222, err: null, ok: 1 } 

And he looks like this when he created a new document:

 { updatedExisting: false, upserted: 51eebc080eb3e2208a630d8e, n: 1, connectionId: 222, err: null, 

(Both cases return numberAffected = 1)

+11
Jul 23 '13 at 17:27
source share

The answer was taken from the book "Applied Model Samples of MongoDB"! determine if upsert was an insert or update

+6
Sep 23 '14 at 10:53 on
source share



All Articles