pymongo - find_one_and_update and write_concern

456 views
Skip to first unread message

Remi Jolin

unread,
Feb 24, 2020, 7:21:04 AM2/24/20
to mongodb-dev
for find_one_and_(update/replace...), uUser manual of pymongo has a warning
Warning
 

Starting in PyMongo 3.2, this command uses the WriteConcern of this Collection when connected to MongoDB >= 3.2. Note that using an elevated write concern with this command may be slower compared to using the default write concern.

 
Does it mean that we cannot specify a write_concern specific to this call anymore (like we could with find_and_modify). 

I tried to use the previous syntax w='majority' for example or write_concern=(ann instance of WriteConcern) and both return traceback 

Shane Harvey

unread,
Feb 24, 2020, 2:38:02 PM2/24/20
to mongodb-dev
I tried to use the previous syntax w='majority' for example or write_concern=(ann instance of WriteConcern) and both return traceback 

It's not possible to specify a 'w' or 'write_concern' to the new write helpers (find_one_and_*, insert_one, insert_many, etc...).

Apps can set the write concern in the connection string for the MongoClient and then all write operations will use the write concern:
>>> client = MongoClient('mongodb://localhost/?w=majority&wTimeoutMS=10000')
>>> client.write_concern
WriteConcern(wtimeout=10000, w=majority)
>>> # All write operations will use WriteConcern(w=majority, wtimeout=10000).
>>> # Collection and Database inherit the write concern from the MongoClient.
>>> coll = client.db.coll
>>> coll.write_concern
WriteConcern(wtimeout=10000, w=majority)
>>> coll.find_one_and_update(query, update) 

The app can also override the write concern when creating new Database or Collection objects:

>>> coll = client.db.get_collection('coll', write_concern=WriteConcern(wtimeout=15000, w='majority'))
>>> coll.write_concern
WriteConcern(wtimeout=15000, w=majority)

Or via Collection.with_options:

>>> new_coll = coll.with_options(write_concern=WriteConcern(wtimeout=1000, w='1'))
>>> new_coll.write_concern
WriteConcern(wtimeout=1000, w=1)


These are the preferred ways to set the write concern. If the app needs to change the write concern for a single operation you can create a new Collection like this:

>>> new_coll = coll.with_options(write_concern=WriteConcern(wtimeout=1000, w='1'))
>>> new_coll.write_concern
WriteConcern(wtimeout=1000, w=1)
>>> new_coll.find_one_and_update(query, update)
Reply all
Reply to author
Forward
0 new messages