Sunday, August 28, 2016

Mongo Three Beginning Python Access

Getting PyMongo


Python has a library, pymongo, that provides a connection with MongoDb. Assuming you have Python installed, to get it you can use the "pip" utility. At the command line you just type:

python -m pip install pymongo

and press Enter. You will see something like this:

install pymongo

Now in your python code you can import the pymongo library.

I am using Microsoft Visual Studio to write the python. It is a much easier environment to work in than IDLE, for me at least. I am not using iron python, which is a version of python that is adapted to compile to the .net byte code. I am just using the Python Application template.

From the pymongo library you also want the MongoClient, and from it you can get the database.

import pymongo
from pymongo import MongoClient

client = MongoClient()
db=client.TechStore

The cursor is an object that will store the results of a query. You just loop through it to get the results.

cursor = db.productCollection.find()

for document in cursor:
    print (document)

Now we will run this.

python query results

You might notice that the way you write a query, looks exactly the way you write a query in the mongo command line client. In fact, they are identical. Just to demonstrate this, I have added two more queries to our simple program.

print("************************")

#find all the products with a price greater than 500
cursor= db.productCollection.find({"price" : {"$gt" : 500}})
for document in cursor:
    print (document)

print("************************")

#find the average of all the prices
cursor = db.productCollection.aggregate([{ "$group" : {"_id" : "null", "averagePrice" : {"$avg" : "$price"}}}])

for document in cursor:
    print (document)

Running the code:

python queries two

Here is the complete code for our little python experiment:

import pymongo
from pymongo import MongoClient

client = MongoClient()
db=client.TechStore

cursor = db.productCollection.find()

for document in cursor:
    print (document)

print("************************")

#find all the products with a price greater than 500
cursor= db.productCollection.find({"price" : {"$gt" : 500}})
for document in cursor:
    print (document)

print("************************")

#find the average of all the prices
cursor = db.productCollection.aggregate([{ "$group" : {"_id" : "null", "averagePrice" : {"$avg" : "$price"}}}])

for document in cursor:
    print (document)
print("************************")

#find the average of all the prices
cursor = db.productCollection.aggregate([{ "$group" : {"_id" : "null", "averagePrice" : {"$avg" : "$price"}}}])

for document in cursor:
    print (document)

Next time I will begin to try to create an actual application that interacts with the mongo database, allowing the user to insert, update and retrieve records--preferably in a graphical way.

No comments:

Post a Comment