0% found this document useful (0 votes)
9 views2 pages

UE20MC505B Unit3 QuestionAnswers

Uploaded by

sreenu_pes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views2 pages

UE20MC505B Unit3 QuestionAnswers

Uploaded by

sreenu_pes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

NoSQL UE20MC505B

Question Answers

1. Find the sum the price of all cars


from pymongo import MongoClient

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))
for i in range(len(v)):
print(v[i])

print('The sum of prices of two cars is {}'.format(v[0]['sum']))

2. Count the number of documents


from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')

with client:

db = client.testdb

n_cars = db.cars.find().count()

print("There are {} cars".format(n_cars))

3. Filter the documents based on price


from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')

with client:

db = client.testdb
exp_cars = db.cars.find({'price': {'$gt': 43000}})
for e in exp_cars:
print(e['name'])

4. Project the documents based on field names

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')

with client:

db = client.testdb

cars=db.cars.find({}, {'_id':0, 'name':1})

for c in cars:
print(c)
NoSQL UE20MC505B
Question Answers

5. Aggregation in Python

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["pes"]
mycol = mydb["employee"]
def insert():
empId = input('Enter Employee id :')
empName = input('Enter Name :')
empSalary = int(input('Enter Salary :'))
empDept = input('Enter the Department')
empAge = int(input('Enter the Age'))
empCity = input('Enter the City')
mycol.insert_one(
{
"id": empId,
"name": empName,
"salary": empSalary,
"dept": empDept,
"age": empAge,
"city": empCity
})
n=input("Entering the number of documents needed")
for i in range(0,int(n)):
insert()

print("All details of Employee")


for x in mycol.find({}, {"_id": 0, "name": 1, "city": 1, "age": 1}):
print(x)

print("The documents inserted are")


for x in mycol.find({}, {"_id": 0, "name": 1, "salary": 1, "dept": 1}):
print(x)

mydoc = mycol.find({"age": {"$gte": 25}}, {"_id": 0, "name": 1})


print("All employees having an age greater than 25")
for x in mydoc:
print(x)

You might also like