How to specify a unsafe/safe write with pymongo's collection.update_one or update_many

1.6k views Asked by At

I have the connection defaulted to w=0 but for collection.update_one or collection.update_many, I want to set the write_concern per operation by setting the parameter w=0. Instead I'm getting this error:

update_one() got an unexpected keyword argument 'w'

What is the right way to do this? I saw that insert accepts 'w' but not update_one or update_many. Why?

1

There are 1 answers

2
A. Jesse Jiryu Davis On BEST ANSWER

The new way to override a PyMongo client's, database's, or collection's write concern is using "with_options":

client = MongoClient(w=0)
collection = client.database.collection
w1_collection = collection.with_options(write_concern=WriteConcern(w=1))
w1_collection.update_one({'_id': 1}, {'$inc': {'x': 3}})

See the docs for write concern and with_options