@@ -143,6 +143,36 @@ of the collections in our database:
143
143
.. note :: The *system.indexes* collection is a special internal
144
144
collection that was created automatically.
145
145
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)
146
176
147
177
Getting a Single Document With :meth: `~pymongo.collection.Collection.find_one `
148
178
------------------------------------------------------------------------------
0 commit comments