Database Reference
In-Depth Information
Chapter 7
Python and MongoDB
Python is one of the easier programming languages to learn and master. It's an especially great language to start with
if you are relatively new to programming. And you'll pick it up that much more quickly if you're already quite familiar
with programming.
Python can be used to develop an application quickly while ensuring that the code itself remains perfectly
readable. With that in mind, this chapter will show you how to write simple yet elegant, clear, and powerful code that
works with MongoDB through the Python driver (also called the PyMongo driver; this chapter will use both terms
interchangeably).
First, you'll look at the Connection() function, which enables you to establish a connection to the database.
Second, you'll learn how to write documents, or dictionaries , as well as how to insert them. Third, you'll learn how
to use either the find() or the find_one() command to retrieve documents using the Python driver. Both of these
commands optionally take a rich set of query modifiers to narrow down your search and make your query a little
easier to implement. Fourth, you'll learn about the wide variety of operators that exist for performing updates. Finally,
you'll take a look at how to use PyMongo to delete your data at the document or even the database level. As an added
bonus, you'll learn how to use the DBRef module to refer to data stored elsewhere.
Let's get started.
Throughout the chapter, you'll see many practical code examples that illustrate the concepts discussed.
The code itself will be preceded by three greater-than ( >>> ) symbols to indicate that the command is written in the
Python shell. The query code will be styled in bold , and the resulting output will be rendered in plaintext.
Note
Working with Documents in Python
As mentioned in earlier chapters, MongoDB uses BSON-styled documents, and PHP uses associative arrays. In a
similar vein, Python has what it calls dictionaries . If you've already played around with the MongoDB console, we're
confident you are absolutely going to love Python. After all, the syntax is so similar that the learning curve for the
language syntax will be negligible.
We've already covered the structure of a MongoDB document in the preceding chapter, so we won't repeat that
information here. Instead, let's examine what a document looks like in the Python shell:
item = {
"Type" : "Laptop",
"ItemNumber" : "1234EXD",
"Status" : "In use",
 
 
Search WWH ::




Custom Search