Write to a Collection Safely and Synchronously

By default, the PyMongo driver performs asynchronous writes. Write operations include insert, update, remove and findAndModify.

Asynchronous writes are unsafe in the sense that they are not checked for errors and so execution of your program could continue without any guarantees of the write having completed successfully. While asynchronous writes improve performance by not blocking execution, they can easily lead to nasty race conditions and other nefarious data integrity bugs. For this reason, we recommend you almost always use safe, synchronous, blocking writes. It seems rare in practice to have truly “fire-and-forget” writes where there are aboslutely no consequences for failures. That being said, one common example where asynchronous writes may make sense is when you are writing non-critical logs or analytics data to MongoDB from your application.

Warning

Unless you are certain you don’t need synchronous writes, we recommend that you pass the “safe=True” keyword argument to inserts, updates, removes and findAndModify operations:

# safe=True ensures that your write
# will succeed or an exception will be thrown
dbh.users.insert(user_doc, safe=True)

Get MongoDB and Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.