For many years I've fought with mongodb when I want to perform an upsert operation that both:
1) returns nModified/nUpserted/etc. result (e.g. https://docs.mongodb.com/manual/reference/method/WriteResult/)
2) returns the id(s) of any modified records. (unfortunately, only an upsert returns WriteResult._id). Returning the fully modified document is even better, but usually my use cases would be sufficient with returning the _id
For example,
db.test.insert({fruit: 'apple'}); db.test.insert({fruit: 'banana'}); db.test.insert({fruit: 'pear'});
db.test.update({fruit: 'orange'}, {$set: {fruit: 'grape'}}, {upsert: true});
will give me nUpserted 1, and _id because the operation resulted in an upsert.
db.test.update({fruit: 'apple'}, {$set: {fruit: 'grape'}}, {upsert: true});
will give me nModified 1, but no _id because the operation was not an upsert.
db.test.findAndModify() returns the record (either old or new as defined by the option), but no WriteResult information so it is not possible to determine if nModified happened or not.
I increasingly find reasons when writing code to want to get this type of information back in one operation.
- related to
-
SERVER-714 Allow findandmodify to retreive more than 1 record at a time
- Open
-
SERVER-28145 add ability to obtain modified flag from findOneAndUpdate result
- Backlog