UE20MC505B_Unit3_LectureNotes
UE20MC505B_Unit3_LectureNotes
Lekha A
Pymongo
Unit 5
Introduction
Pymongo is a python distribution containing tools for working with mongodb and is
the recommended way to work with mongodb from python.
Prerequisite
Python 3 and mongodb should be installed.
Start the mongodb server.
Installation
For Linux/mac OS platforms, issue the below command to add the <pymongo driver>.
sudo pip install pymongo
For windows platforms, issue the below command to add the <pymongo driver>
python -m pip install pymongo
To get a specific version of pymongo:
python -m pip install pymongo==3.9.0
To upgrade using pip
python -m pip install --upgrade pymongo
To drop the created mongodb collection after completing the transactions call the
method as given below.
con.drop()
Programs
1. #Program to create a db called pes and collection mca that contains 10
#documents having same value in field 'name'
import pymongo
from pymongo import MongoClient
# connect to the db on standard port
conn = pymongo.MongoClient("mongodb://localhost")
for i in range(10):
coll.insert_one({"name": "Lekha"})
docs = coll.find()
for i in docs:
print(i)
#coll.drop();
2. #Program to create a db called pes and collection mca that contains 10
#documents having field 'name' taken randomly from a dictionary called
#'people', 'number' having a random generated between 0 and 100 and
#user_id
import pymongo
import math
import random
for i in range(10):
user_id = i;
name = people[int(math.floor(random.random()*len(people)))];
number = math.floor(random.random()*100);
x = { "user_id": user_id, "name": name, "number": number };
coll.insert(x);
#num = coll.find().count()
#Using the docs try to get the number of records present in the
#collection
num=docs.count()
print(num)
import pymongo
import math
import random
def insert():
people = ['lekha', 'isha', 'krishna', 'manish', 'varshini',
'pushpa']
for i in range(10):
user_id = i;
name = people[int(math.floor(random.random()*len(people)))];
number = math.floor(random.random()*100);
x = { "user_id": user_id, "name": name, "number": number };
coll.insert(x);
insert()
try:
docs = coll.find()
for i in docs:
print(i)
except Exception as e:
print ("Error trying to read collection:", type(e), e)
num = coll.find().count()
print(num)
4. #Program to update a db called pes and collection mca and Update with
all #names as Lekha
import pymongo
import math
import random
from pymongo import MongoClient
docs = coll.find()
for i in docs:
print(i)
num = coll.find().count()
print("The total records updated are")
print(num)
db = connection.pes # attach to db
collection = db.mca # specify the collection
collection.insert_one(st)
q = {'name': 'Lekha'}
p = {'_id': 0, 'name': 1}
doc = collection.find(q, p)
for d in doc:
print (d)
print(doc.count())
doc = collection.find()
for d in doc:
print (d)
print(doc.count())
6. #Program using the function add to insert document into the collection
#called mca and database called pes
import pymongo
import math
import random
try:
database = conn.pes # attach to db
coll = database.mca # specify the collection
def add():
people = ['lekha', 'isha', 'krishna', 'manish', 'varshini',
'pushpa']
for i in range(10):
user_id = i;
name = people[math.floor(random.random()*len(people))];
number = math.floor(random.random()*100);
x = { "user_id": user_id, "name": name, "number": number };
coll.insert(x);
add()
except Exception as e:
num = coll.find().count()
print(num)
import pymongo
import sys
from pymongo import MongoClient
db = connection.pes # attach to db
collection = db.emp # specify the collection
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pes"]
mycol = mydb["customers"]
def insert():
custId = input('Enter Customer id :')
custName = input('Enter Name :')
custAge = int(input('Enter age :'))
custAddress = input('Enter Address :')
mycol.insert_one(
{
"id": custId,
"name": custName,
"age": custAge,
"address": custAddress
})
for i in range(0,int(n)):
insert()
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pes"]
mycol = mydb["employee"]
def insert():
empId = input('Enter Customer id :')
empName = input('Enter Name :')
empSalary = int(input('Enter Salary :'))
empDept = input('Enter the Department')
mycol.insert_one(
{
"id": empId,
"name": empName,
"salary": empSalary,
"dept": empDept
})
print(x)
pipe = [{'$group' : {'_id' : 'null', 'salary_sum' : {'$sum' :
"$salary"}}}]
print("sum of salary of all employees")
for x in mycol.aggregate(pipeline = pipe):
print(x)
print(" sum of salary of all employee in same department where salary >
800000")
pipe=[
{ '$match': { 'salary' : { '$gt': 800000} } },
{'$group' : {'_id' : "$dept", 'salary_sum' : {'$sum' : "$salary"}}}]
for x in mycol.aggregate(pipeline = pipe):
print(x)
10. Read all records from the collection. Use Python for loop to traverse the
returned cursor
#!/usr/bin/python3
#In the following example, we
.
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.testdb
cars = db.cars.find()
#!/usr/bin/python3
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.testdb
a = [{'$group':{'_id':1, 'sum':{'$sum':'$price'}}}]
v = list(db.cars.aggregate(a))
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.testdb
print(db.list_collection_names())
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.testdb
a = [{'$match': {'$or': [{'name': "Skoda"}, {'name': "Tata"}]}},
{'$group': {'_id' : 1, 'sum' : {'$sum':'$price'}}}]
v = list(db.cars.aggregate(a))
client = MongoClient('mongodb://localhost:27017/')
mydb = client['test-database']
mydb.posts.drop()
import datetime
post = {
"author": "Lekha ",
"title" : "PyMongo 101 - 5",
"tags" : ["MongoDB 5", "PyMongo 101 - A5", "Tutorial 5"],
"date" : datetime.datetime.utcnow()
}
posts = mydb.posts
post_id = posts.insert_one(post)
print(mydb.list_collection_names())
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.testdb
cars = db.cars.find().sort("price", -1)
for c in cars:
print('{0} {1}'.format(c['name'], c['price']))
16. Statistics of use of one database
#!/usr/bin/python3
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.testdb
print(db.list_collection_names())
status = db.command("dbstats")
pprint(status)
import json
db = client['pes']
col1 = db['prizes']
col2= db['laureates']
col1.drop()
col2.drop()
with open('prizes.json') as f:
file_data = json.load(f)
# Create a filter for laureates who died in the USA but were born in Austria
criteria = {"diedCountry": "USA",
"bornCountry": "Austria"}
# Create a filter for laureates who died in the Austria but were born in
Austria
criteria = {"diedCountry": "Austria",
"bornCountry": "Austria"}
# Create a filter for Germany-born laureates who died in the USA and with the
first name "Albert"
criteria = {"bornCountry": "Germany",
"diedCountry": "USA",
"firstname": "Albert"}
# Save a filter for laureates who died in the USA and were not born there
criteria = { "diedCountry": "USA",
# Count them
count = db.laureates.count_documents(criteria)
print(count)