Home > Articles > Open Source > Python

Hit the Ground Running with MongoDB and Python

Stephen B. Morris describes how to get started with MongoDB and Python. As usual with Python, you can get productive quickly, without worrying about complex IDEs. MongoDB has a simple data model and easy-to-understand semantics, giving you a handy on-ramp to this interesting technology.
Like this article? We recommend

NoSQL database engines such as MongoDB are pretty trendy at the moment. Every programmer I've talked to in the last couple of years seems to want to work with one of the NoSQL database engines! The argument most often cited in favor of using this technology is enhanced scalability. I'm not so sure about the scalability issue in all cases, but NoSQL technologies definitely have some solid use cases, as opposed to those of relational databases.

Aside from the desire of programmers (myself included) to work with the latest technologies, there are certain reasons for using MongoDB and other NoSQL products. As with most things in IT, language selection often comes down to cost. Lately I've noticed a move toward using more lightweight technologies in an effort to simplify IT development and maintenance.

My articles "Protect C++ Legacy Programs by Using Python" and "Exception Management in C++ and Python Development: Planning for the Unexpected" discuss programming languages at some length, focusing on Java and Python. One theme of these articles is the relative ease with which Python code can be developed, as compared to Java code. Of course, Java solutions are more heavyweight, bringing benefits such as out-of-the-box thread-safety, strong typing, and security. By contrast, in many cases Python allows you to get to a first-draft prototype much more quickly, which is one reason why many organizations are now building prototypes using Python. The Python prototype is tested and then replaced by an implementation in Java (or whatever is the preferred mainstream high-level language).

The allied area of databases is another key element in the IT cost base. License costs aren't really the issue; high-performance, open source database engines such as MySQL are widely available and have been proven over many years of use. Rather, key costs have more to do with software development and maintenance expenses.

Installing and Running MongoDB

With these issues in mind, let's see how the interesting combination of MongoDB and Python stacks up. As always, a good place to start is installing and playing around with a test system. I used Ubuntu 12.04.4 LTS for the examples in this article, but that setup isn't mandatory.

Getting MongoDB up and running is pretty straightforward: Just run the five commands in Listing 1 to install and start MongoDB.

Listing 1—Installation and startup for MongoDB.

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart
 dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
sudo apt-get update
sudo apt-get install mongodb-org
sudo service mongod start

The last command in Listing 1 may actually be superfluous, because the installation starts the service by default. I include the command just in case the engine doesn't start automatically.

To verify that MongoDB is running, use this command:

/etc/init.d/mongod status

This command should produce a status message with content similar to that in Listing 2.

Listing 2—MongoDB is running.

Rather than invoking init scripts through /etc/init.d, use the service(8)

utility, e.g. service mongod status

Since the script you are attempting to invoke has been converted to an

Upstart job, you may also use the status(8) utility, e.g. status mongod

mongod start/running, process 11969

If all has gone well with the installation, you should now have a working MongoDB installation. Nice and easy!

Now let's try to use the database engine. The following examples are based on those in the MongoDB online manual.

Connecting to MongoDB

It's easy to connect to MongoDB: Just type this:

mongo

This command should launch the MongoDB shell and display the text shown in Listing 3 (or something similar):

Listing 3—Connecting to MongoDB.

MongoDB shell version: 2.6.3

connecting to: test

Server has startup warnings: 

2014-07-30T16:34:05.028+0100 [initandlisten] 

2014-07-30T16:34:05.028+0100 [initandlisten] ** NOTE: This is a 32 bit MongoDB binary.

2014-07-30T16:34:05.028+0100 [initandlisten] **       32 bit builds are limited to less than 2GB of data (or less with --journal).

2014-07-30T16:34:05.028+0100 [initandlisten] **       Note that journaling defaults to off for 32 bit and is currently off.

2014-07-30T16:34:05.028+0100 [initandlisten] **       See http://dochub.mongodb.org/core/32bit

2014-07-30T16:34:05.028+0100 [initandlisten] 

> 

In Listing 3, notice that the very last line provides the console prompt (>) for interacting with MongoDB. In the remainder of this article, I'll describe some commands that can be typed at the console. To start using the console, display the current (default) MongoDB database by using this command:

db

This command produces the following output:

> db

test

To view all databases, use this command:

> show dbs

admin     (empty)

local     0.078GB

mydb      0.078GB

testData  0.078GB

To use a specific database, type the following command, followed by db to verify that the correct database context has been selected:

> use mydb

switched to db mydb

Now, check the selected database:

> db

mydb

We've verified that the selected database is mydb. Now let's add some data to mydb. Remember that MongoDB is an open source document-centric database engine. This is a very different model from the more rigid relational-database world. You must create documents and then add them to Mongo. It might sound difficult, but it's easy to do:

> j = { name : "mongo" }

{ "name" : "mongo" }

This command creates a document called j, which is a field-value pair. It can then be written into MongoDB as follows:

> db.mydb.insert(j)

WriteResult({ "nInserted" : 1 })

This example illustrates another important MongoDB principle: MongoDB is a dynamic schema technology. There's no need to define the schema statically.

Now let's add another document called j:

> j = { name : "mongo", age : "25" }

> db.mydb.insert(j)

To retrieve the inserted documents, type this:

> db.mydb.find()

{ "_id" : ObjectId("53d9156445db8daa9930cfe2"), "name" : "mongo" }

{ "_id" : ObjectId("53d9176445db8daa9930cfe3"), "name" : "mongo", "age" : "25" }

Notice that both records have been retrieved from MongoDB. Each record also has acquired an ObjectId field, created automatically (on insertion) by MongoDB, which serves to distinguish it from other records. Another aspect to note is the JSON-like structure of the data.

Cursors and Looping

It's also possible to use a cursor and loop over all of the returned data. This technique is beneficial as the data set grows. To get a cursor, just use the following command:

> var c = db.mydb.find()

Next, iterate over the cursor as follows:

> while (c.hasNext()) printjson(c.next()){ "_id" : ObjectId("53d9156445db8daa9930cfe2"), "name" :
 "mongo" }{       "_id" : ObjectId("53d9176445db8daa9930cfe3"),       "name" : "mongo",       "age" : "25"}

As you can verify, the two documents we saved earlier were found in the cursor iteration. Notice the use of printjson(), which renders the data in a JSON-like format. Isn't JSON a close relation of JavaScript? It turns out that the use of this JSON-like format provides additional flexibility in the use of MongoDB.

Using JavaScript with MongoDB

The mongo shell isn't the only option for interacting with a MongoDB installation; you can also use JavaScript files as an alternative means of access. A scripted interface provides a more powerful facility than the straight console. This is because your script can be large or small and contain an arbitrarily large number of commands. However, the JavaScript command format is a bit different from the straight MongoDB shell. Using JavaScript as an access technology places MongoDB in close proximity to other web technologies.

Specific Querying

To query a specific document in the database, just use the associated data values:

> db.mydb.find( { name : "mongo", age : "25" } )

{ "_id" : ObjectId("53d9176445db8daa9930cfe3"), "name" : "mongo", "age" : "25" }

Notice that the query above returned just one of the two documents in the mydb database context.

Our basic MongoDB installation is complete and verified! Now let's get some Python tools installed and working.

Installing PyMongo

PyMongo is a Python distribution designed for working with MongoDB. I've found that the easiest way to install PyMongo is by using Python pip. To get started, let's install pip:

sudo apt-get install python-pip

Next, install PyMongo:

sudo pip install pymongo

This command should produce something like the following:

Downloading/unpacking pymongo

  Running setup.py egg_info for package pymongo

Installing collected packages: pymongo

  Running setup.py install for pymongo

Successfully installed pymongo

Cleaning up...

When you see the results above, you should be ready to start running some PyMongo code. As usual, I start with the easiest option: the Python console. Type the following command from a Linux console:

python

You should get something like the following result:

Python 2.7.3 (default, Feb 27 2014, 20:00:17) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

Now verify that PyMongo has been installed:

>>> import pymongo

If you get no errors from this import statement, then PyMongo has been installed successfully.

Next, import and instantiate the MongoClient:

>>> from pymongo import MongoClient

>>> client = MongoClient()

It's useful to print out the details of the client object. Notice that the default host and port number have been used (if you prefer, you can specify these details when the client is created):

>>> clientMongoClient('localhost', 27017)

Listing PyMongo Databases

To view the databases, use this Python statement on the client object:

>>> client.database_names()

[u'mydb', u'testData', u'local', u'admin']

Now get a connection to the mydb database, as follows:

>>> db = client.mydb

Listing PyMongo Database Collections

Get a list of the collections:

>>> db.collection_names()

[u'testData', u'system.indexes', u'mydb']

Interacting with a Collection

To get the first document from a given collection, use this command:

>>> db.mydb.find_one()

{u'_id': ObjectId('53d9156445db8daa9930cfe2'), u'name': u'mongo'}

To get a specific item from a collection, add the required attributes to the search:

>>> db.mydb.find_one({"name": "mongo"})

{u'_id': ObjectId('53d9156445db8daa9930cfe2'), u'name': u'mongo'}

To extend the search parameters, just add more attributes:

>>> db.mydb.find_one({"name": "mongo", "age":"25"})

{u'age': u'25', u'_id': ObjectId('53d9176445db8daa9930cfe3'), u'name': u'mongo'}

To see how a failed search looks, just add an invalid attribute:

>>> db.mydb.find_one({"name": "mongo", "age":"26"})

As you can see, it's pretty easy getting into this clever technology! Now it's time to write some Python code to interact with MongoDB programmatically.

Using Python to Insert Data into MongoDB Databases

Let's see how to insert time-stamped data into MongoDB by using Python:

>>> import datetime

Next, create an object to insert:

>>> post = {"author": "Mick",

...     "text": "My very first blog post",

...     "tags": ["mongodb", "python", "pymongo"],

...     "date": datetime.datetime.utcnow()}

View the newly created object:

>>> post

{'date': datetime.datetime(2014, 7, 31, 11, 57, 11, 535966), 'text':
 'My very first blog post', 'tags': ['mongodb', 'python', 'pymongo'], 'author': 'Mick'}

Before we can insert this object into a database, we need to create a new collection, here called posts:

>>> posts = db.posts

Verify that the new collection has been created in the database:

>>> db.collection_names()
[u'testData', u'system.indexes', u'mydb', u'posts']

Now we can add the post document into the collection:

>>> post_id = posts.insert(post)

If no error message is presented, then the posts data has been written successfully to MongoDB. You can verify this result by printing out the value of post_id:

>>> post_id
ObjectId('53da301d83cc1d283b1df18a')

As before, we can view the first entry in the new collection:

>>> posts.find_one()

{u'date': datetime.datetime(2014, 7, 31, 11, 57, 11, 535000), u'text':
 u'My very first blog post', u'_id': ObjectId('53da301d83cc1d283b1df18a'),
 u'author': u'Mick', u'tags': [u'mongodb', u'python', u'pymongo']}

Notice that the ObjectId value matches that returned by post_id above.

Searching MongoDB with PyMongo

Before performing any searches, let's add another document to the new collection, using the same procedure as described earlier:

>>> post = {"author": "Frank",

...     "text": "My first blog posting",

...     "tags": ["java","mongodb","python"],

...     "date": datetime.datetime.utcnow()}

>>> post

{'date': datetime.datetime(2014, 7, 31, 12, 12, 59, 74803), 'text': 'My first blog posting',
 'tags': ['java', 'mongodb', 'python'], 'author': 'Frank'}

>>> post_id = posts.insert(post)

>>> post_id

ObjectId('53da32dd83cc1d283b1df18b')

As before, let's try to search for one of the authors, thereby forcing MongoDB to differentiate between the records in the collection:

>>> posts.find_one({"author":"Mick"})

{u'date': datetime.datetime(2014, 7, 31, 11, 57, 11, 535000), u'text':
 u'My very first blog post', u'_id': ObjectId('53da301d83cc1d283b1df18a'),
 u'author': u'Mick', u'tags': [u'mongodb', u'python', u'pymongo']}

We've found the first author. Changing the author attribute name to Frank, search again:

>>> posts.find_one({"author":"Frank"})

{u'date': datetime.datetime(2014, 7, 31, 12, 12, 59, 74000), u'text': u'My first blog posting',
 u'_id': ObjectId('53da32dd83cc1d283b1df18b'), u'author': u'Frank', u'tags': [u'java', u'mongodb', u'python']}

Again, we retrieve the required item successfully. But what happens if we search on an unknown item?

>>> posts.find_one({"author":"John"})

Nothing comes back from MongoDB, because no item exists with that attribute name.

A Note About Running Python Example Code

I've often commented on the lightweight nature of Python. In this article, I've used the Python console exclusively. In Linux, this is simple to do, and it avoids the distraction of trying to install a complex IDE. Having struggled with such IDEs for years, I've found great pleasure in being able to get rapidly into a new technology in this way! Running the python console results in something similar to that illustrated in Listing 4:

Listing 4—The Python console, checking whether PyMongo is installed.

Python 2.7.3 (default, Sep 26 2013, 20:08:41)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

As shown earlier, here's how to see whether PyMongo is installed:

>>> import pymongo
>>>

Obviously, as the code examples become more complex, copying-and-pasting into a console can get a bit clunky. At a certain point, you'll need to install an IDE. But at least you'll be comfortable with the technology before doing that.

Conclusion

MongoDB is a pretty trendy product at the moment. As one of the NoSQL database engines, MongoDB provides for a fairly permissive database experience (compared to that of a relational database). The MongoDB schema is dynamic, which allows you to insert data in a very flexible way. One of the key use cases for MongoDB is storing unstructured data, such as from sensor arrays. In such networks, massive amounts of data is generally the rule. MongoDB can comfortably chomp away at such data streams, providing a resilient repository. Creating MongoDB test data is also easy, using a simple piece of code such as this:

for (var i = 1; i <= 10000; i++) db.mydb.insert( { x : i } )

This line of code inserts 10,000 documents.

Getting set up with MongoDB is pretty easy; perhaps the only confusing thing is understanding the connection between databases and collections. Once you try it out, however, that relationship becomes clear.

The console that comes with MongoDB allows you to experiment with data insertion and searching. Scripted interaction with MongoDB is also possible, and you can save such scripts as JavaScript files and execute them directly. The data format of choice is JSON-like, again placing this engine in a very modern context, where increasingly JSON and JavaScript are technologies of choice.

The Python world has embraced MongoDB, and it's easy to get started with PyMongo. Indeed, this is reminiscent of getting up and running with SQLAlchemy for relational database access through Python (see my article "Database Development: Comparing Python and Java ORM Performance" for details).

This article has barely scratched the surface of MongoDB. The technology also supports advanced implementation issues such as sharding, aggregation, security, and indexing.

References

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020