Friday, 10 August 2012

Pymongo

In the previous blog about Mongodb which mainly dealt with javascript. But mongo version is also available for python users. It is almost similar and provides the same functionalities too. Pymongo is a python distribution to work with Mongodb.

Installation pymongo

 For Linux versions we will install sing pip.

$sudo pip install pymongo

Next to install dependencies in ubuntu/debian systems

 $ sudo apt-get install build-essential python-dev 

Getting started with pymongo

If pymongo is already installed you would be able to easily import it in the python prompt without raising an exception.

>>> import pymongo

Now the first step is to create a connection to the running mongod instance.
 
>>> from pymongo import Connection
>>> connection = Connection()

We can also connect to a specific network by specifying it in Connection('network',no.).

You can use the connection instance to access independent databases by applying any style either 

>>> db = connection.test_database
  
 or dictionary style

>>> db = connection['test-database']

A collection is a group of documents stored in a mongodb, similar to a table in RDBMS. The collection can be accessed similar to databasein both the above mentioned ways.

>>> collection = db.test_collection
>>> collection = db['test-collection'] 
  
Pymongo uses dictionary style for storing documents. Example of a document representing simple text is given below:-

 >>>import datetime
>>> post = {"author": "anjali", "text": "working with pymongo","date":datetime.datetime.utcnow()}

To insert document into a collection we can do the following-

>>> posts = db.post
>>> posts.insert(post)
ObjectId('5024d44b3e22462b281395f4')

This creates the first document in the server, which can be verified by-

>>> db.collection_names()
[u'test', u'system.indexes', u'things', u'post']

 
Similar to Sel in RDBMS SQL, we have find_one() which returns the  document matching the query.

>>> posts.find_one()
{u'date': datetime.datetime(2012, 8, 10, 9, 27, 24, 746000), u'text': u'working with pymongo', u'_id': ObjectId('5024d44b3e22462b281395f4'), u'author': u'anjali'}

You can also do specific querying by providing a particular condition in the find_one.Eg:-

>>> posts.find_one({"author":"anjali"})
{u'date': datetime.datetime(2012, 8, 10, 9, 27, 24, 746000), u'text': u'working with pymongo', u'_id': ObjectId('5024d44b3e22462b281395f4'), u'author': u'anjali'}
For a query which doesn't have a match we get like below:-

>>>posts.find_one({"author":"radha"})
>>>
Bulk inserts are also supported in pymongo by giving a list of dictionaries.Eg:-

>>> more_posts = [{"author":"Devi","text":"mongo is simple"},{"author":"resmy","text":"I like SQL more "}]
>>> posts.insert(more_posts)
[ObjectId('5024df513e22462b281395f5'), ObjectId('5024df513e22462b281395f6')]
>>>
 

Querying for more than one document is also supported using for loops-

>>> for post in posts.find():  
...   post
...
{u'date': datetime.datetime(2012, 8, 10, 9, 27, 24, 746000), u'text': u'working with pymongo', u'_id': ObjectId('5024d44b3e22462b281395f4'), u'author': u'anjali'}
{u'text': u'mongo is simple', u'_id': ObjectId('5024df513e22462b281395f5'), u'author': u'Devi'}
{u'text': u'I like SQL more ', u'_id': ObjectId('5024df513e22462b281395f6'),
u'author': u'resmy'}
>>>

Similarly search for a particular document can be done by providing a condition to be searched on in find().

Another function count returns the number of documents present in a collection either based on a condition or simply the total.

>>> posts.find({"author":"anjali"}).count()
1

We can also make our querying based on some index value. First we create an index and query the document.

>>> from pymongo import ASCENDING, DESCENDING
>>> posts.create_index([("date", DESCENDING), ("author", ASCENDING)])
u'date_-1_author_1'
>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["cursor"]
u'BtreeCursor date_-1_author_1'
>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["nscanned"]
2
 
Pymongo is a tool for experimenting with NoSQL databases. This shows again how python in helpful in bridging any variants.

No comments:

Post a Comment