Laizer
Laizer

Reputation: 6140

Using write concern with insert_one

I'm upgrading to pymongo 3.6+ from earlier versions. The collection save() method is now deprecated, and insert_one is the recommended replacement. I'm used to using a write concern w=1 on the save() method, and it's not clear to me from documentation how to properly enforce a write concern when using insert_one(). How should I go about that in the late 3.x and early 4.x versions?

Upvotes: 2

Views: 2376

Answers (3)

Graham Moss
Graham Moss

Reputation: 41

You can use the with_options method. Example:

from pymongo.write_concern import WriteConcern
db.users.with_options(write_concern=WriteConcern(w="majority")).insert_one({"name": name, "email": email})

Upvotes: 4

Andresse Njeungoue
Andresse Njeungoue

Reputation: 608

You can doing something like this in your code...

from pymongo.write_concern import WriteConcern
db.users.with_options(
    write_concern=WriteConcern(w="majority")
).insert_one(
      {"name": name, "email": email}
  )

Upvotes: 1

Laizer
Laizer

Reputation: 6140

Best I can tell, write concern is now set globally, and individual insert_one operations can not change that write concern. The default write concern is w=1, meaning that acknowledgement is given. PyMongo provides an interface to modify the global write concern.

Upvotes: 1

Related Questions