Database Reference
In-Depth Information
In the examples in this section, we will assume that the following code (or something similar)
has set up an event from the Apache Log. In a real system, of course, we would need code to
actually parse the log and create the Python dict shown here:
>>>
>>> import
import bson
bson
>>>
>>> import
import pymongo
pymongo
>>>
>>> from
from datetime
datetime import
import datetime
>>>
>>> conn = pymongo . Connection ()
>>>
>>> db = conn . event_db
>>>
>>> event = {
...
...
_id : bson . ObjectId (),
...
host : "127.0.0.1" ,
...
time : datetime ( 2000 , 10 , 10 , 20 , 55 , 36 ),
...
path : "/apache_pb.gif" ,
...
referer : "[http://www.example.com/start.html](http://www.example.com/..." ,
...
user_agent : "Mozilla/4.08 [en] (Win98; I ;Nav)"
...}
The following command will insert the event object into the events collection:
>>>
>>> db . events . insert ( event , w = 0 )
By setting w=0 , you do not require that MongoDB acknowledge receipt of the insert. Although
this is the fastest option available to us, it also carries with it the risk that you might lose a
large number of events before you notice.
If you want to ensure that MongoDB acknowledges inserts, you can omit the w=0 argument,
or pass w=1 (the default) as follows:
>>>
>>> db . events . insert ( event )
>>>
>>> # Alternatively, you can do this
>>>
>>> db . events . insert ( event , w = 1 )
MongoDB also supports a more stringent level of write concern, if you have a lower tolerance
for data loss. MongoDB uses an on-disk journal file to persist data before writing the updates
back to the “regular” data files.
Since journal writes are significantly slower than in-memory updates (which are, in turn,
much slower than “regular” data file updates), MongoDB batches up journal writes into
“group commits” that occur every 100 ms unless overridden in your server settings. What this
Search WWH ::




Custom Search