I. Install pymongo
Installing pymongo by easy_instal. In terminal, just type:sudo easy_install pymongoIf your computer haven't installed easy_install yet. You will face with the message :
The program 'easy_install' is currently not installed. You can install it by typing: sudo apt-get install python-setuptoolsJust type:
sudo apt-get install python-setuptoolsfirst. After that type easy_install command that I mentioned above to get Pymongo.
II. Test connection with MongoDb
After finishing installation, Let's test Pymongo by using the following python commands in terminal.1.Get connection, show all document databases of mongodb
By importing pymongo, making a connection and use database_names() command to get the list of current databases in mongodb.# use the following command step by step in terminal import pymongo #get Client client = pymongo.MongoClient("localhost", 27017) #show all mongo document databases client.database_names()In my PC,2 databases are existed ( the image belows). They are test and local.
2.Show all collections of a Document database in mongoDb
# choose a database db = client.test # show all collections of test database db.collection_names()
Find, insert, update, save, remove documents using pymongo
Insert new document and see the result by find all documents in Test collection.# insert new document to collection collection.insert({'hello':'hello codingtip.blogspot.com'}) # print all item in test collection for item in collection.find(): ... print item
Update current document
#update current document collection.update({'hello':'hello codingtip.blogspot.com'},{'$set':{'reply':'hi!'}}) # print all item in test collection for item in collection.find(): ... print item
Remove all documents in current Collection:
#remove all documents in current collection collection.remove() # print all item in test collection for item in collection.find(): ... print item