Skip to content

Commit 1308e02

Browse files
committed
Explain the importance of safe=True in the tutorial.
1 parent 6fdcce2 commit 1308e02

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

doc/tutorial.rst

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,36 @@ of the collections in our database:
143143
.. note:: The *system.indexes* collection is a special internal
144144
collection that was created automatically.
145145

146+
Ensuring Your Insert Succeeded
147+
------------------------------
148+
149+
PyMongo’s default behavior for :meth:`~pymongo.collection.Collection.insert`,
150+
:meth:`~pymongo.collection.Collection.update`,
151+
:meth:`~pymongo.collection.Collection.save`,
152+
and :meth:`~pymongo.collection.Collection.remove` is to perform unacknowledged
153+
writes: the driver does not request a response or wait for an acknowledgement
154+
that the operation was successful unless the method is passed safe=True or
155+
another `getLastError <http://www.mongodb.org/display/DOCS/getLastError+Command>`_
156+
option. For example, if two documents with the same ``_id`` are inserted:
157+
158+
.. doctest::
159+
160+
>>> db.posts.insert({'_id': 1})
161+
1
162+
>>> db.posts.insert({'_id': 1})
163+
1
164+
165+
Both inserts appear to succeed, but the second failed on the server.
166+
To see why, we need to pass safe=True
167+
to :meth:`~pymongo.collection.Collection.insert`::
168+
169+
>>> db.posts.insert({'_id': 1}, safe=True)
170+
Traceback (most recent call last):
171+
pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: test-database.posts.$_id_ dup key: { : 1 }
172+
173+
Applications should generally set a default of safe=True when they first create a Connection::
174+
175+
>>> connection = Connection('localhost', 27017, safe=True)
146176

147177
Getting a Single Document With :meth:`~pymongo.collection.Collection.find_one`
148178
------------------------------------------------------------------------------

0 commit comments

Comments
 (0)