简体   繁体   中英

Mongodb: Getting upsert result in pymongo

Mongo returns a WriteResult on upserts:

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Is there any way I could access those fields from pymongo? I need this because an update always returns none in pymongo and I want to know if the document I was querying was modified or even if it exists without doing an additional query. Can you please tell me how this could be done?

PS I know this has been asked before but it was a few years ago and everything I could found on google didn't include an example.

Since we're at it, is there a way to get fields from the document from the result of an upsert? (or at least the _id)

Solved: As Neil Lunn suggests, the Bulk API is the way to go if you want to get more data out of what happened with your updates. I'd just like to point out this quick walkthrough of the API.

The newer MongoDB shell implementations from MongoDB 2.6 and upwards actually define there shell helper methods for .update() and .insert() etc, using the "Bulk operations API" where this is available.

So basically where the shell is connecting to aa MongoDB 2.6 instance or greater the "Bulk" methods are used "under the hood". Even if they actually are only acting on one document at a time, or otherwise effectively only issuing "one" update request or similar.

The general driver interfaces have not yet caught up with this and you need to still invoke explicitly:

bulk = db.test.initialize_ordered_bulk_op()

bulk.find({}).upsert().update({ "$set" { "this": "that" } }

result = bulk.execute()

The "result" returned here matches the "Bulk Write Result" specification you see in the shell, which is different to how the "legacy" implementations which are currently used in the standard driver methods return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM