Hit the Ground Running with MongoDB and Python
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 1Installation 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 2MongoDB 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 3Connecting 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 4The 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.