Database Reference
In-Depth Information
"Location" : {
"Department" : "Development",
"Building" : "2B",
"Floor" : 12,
"Desk" : 120101,
"Owner" : "Anderson, Thomas"
},
"Tags" : ["Laptop","Development","In Use"]
}
While you should keep the Python term dictionary in mind, in most cases this chapter will refer to its MongoDB
equivalent, document . After all, most of the time, we will be working with MongoDB documents.
Using PyMongo Modules
The Python driver works with modules. You can treat these much as you treat the classes in the PHP driver. Each
module within the PyMongo driver is responsible for a set of operations. There's an individual module for each of
the following tasks (and quite a few more): establishing connections, working with databases, leveraging collections,
manipulating the cursor, working with the DBRef module, converting the ObjectId , and running server-side
JavaScript code.
This chapter will walk you through the most basic yet useful set of operations needed to work with the PyMongo
driver. Step-by-step, you'll learn how to use commands with simple and easy-to-understand pieces of code that you
can copy and paste directly into your Python shell (or script). From there, it's a short step to managing your MongoDB
database.
Connecting and Disconnecting
Establishing a connection to the database requires that you first import the PyMongo driver's MongoClient module,
which enables you to establish connections. Type the following statement in the shell to load the MongoClient module:
>>> from pymongo import MongoClient
Once your MongoDB service is up and running (this is mandatory if you wish to connect), you can establish a
connection to the service by calling the MongoClient() function.
If no additional parameters are given, the function assumes that you want to connect to the service on the
localhost (the default port number for the localhost is 27017). The following line establishes the connection:
>>> c = MongoClient()
You can see the connection coming in through the MongoDB service shell. Once you establish a connection, you
can use the c dictionary to refer to the connection, just as you did in the shell with db and in PHP with $c . Next, select
the database that you want to work with, storing that database under the db dictionary. You can do this just as you
would in the MongoDB shell—in the following example, you use the inventory database:
>>> db = c.inventory
>>> db
Database(Connection('localhost', 27017), u'inventory')
The output in this example shows that you are connected to the localhost and that you are using the
inventory database.
 
Search WWH ::




Custom Search