Databases Reference
In-Depth Information
• If you want to live longer, save valuable user input (account sign-ups, credit card
numbers, emails) with safe operations and do everything else with fire-and-forget
operations.
• If you are cautious, use safe operations exclusively. If your application is automat-
ically generating hundreds of little pieces of information to save (e.g., page, user,
or advertising statistics), these can still use the fire-and-forget operation.
Catching “Normal” Errors
Safe operations are also a good way to debug “strange” database behavior, not just for
preventing the apocalyptic scenarios described earlier. Safe operations should be used
extensively while developing, even if they are later removed before going into produc-
tion. They can protect against many common database usage errors, most commonly
duplicate key errors.
Duplicate key errors often occur when users try to insert a document with a duplicate
value for the "_id" key. MongoDB does not allow multiple documents with the same
"_id" in the same collection. If you do a safe insert and a duplicate key error occurs,
the server error will be picked up by the safety check, and an exception will be thrown.
In unsafe mode, there is no database response, and you might not be aware that the
insert failed.
For example, using the shell, you can see that inserting two documents with the same
"_id" will not work:
> db.foo.insert({"_id" : 123, "x" : 1})
> db.foo.insert({"_id" : 123, "x" : 2})
E11000 duplicate key error index: test.foo.$_id_ dup key: { : 123.0 }
If we examine the collection, we can see that only the first document was successfully
inserted. Note that this error can occur with any unique index, not just the one on
"_id" . The shell always checks for errors; in the drivers it is optional.
Requests and Connections
For each connection to a MongoDB server, the database creates a queue for that con-
nection's requests. When the client sends a request, it will be placed at the end of its
connection's queue. Any subsequent requests on the connection will occur after the
enqueued operation is processed. Thus, a single connection has a consistent view of
the database and can always read its own writes.
Note that this is a per-connection queue: if we open two shells, we will have two con-
nections to the database. If we perform an insert in one shell, a subsequent query in
the other shell might not return the inserted document. However, within a single shell,
if we query for the document after inserting, the document will be returned. This be-
havior can be difficult to duplicate by hand, but on a busy server, interleaved inserts/
 
Search WWH ::




Custom Search