Saturday, January 10, 2015

How to retrieve data from MongoDB using Python

First PyMongo module should install according to the Python version that you are going use. You can find the PyMongo in the following link:
Then, create a database and collection on MongoDB with database name: mydb and collection Name: friends as shown below.
The following code will retrieve the data as shown below.
Code:
*******************************************************************
import pymongo
from pymongo import MongoClient


#connect to Database
connection = MongoClient('localhost', 27017)
db = connection.mydb


#handle to friends Collection
data = db.friends


friendsList = data.find()


for item in friendsList:

   print("Name: " + item["name"] + "Age: " + str(item["age"]))
******************************************************************

Cheers!
Uma

6 comments: