Write a Python program that can perform verious operations on MongoDB.
Program
import pymongo as pm
#Connection Establishment
client = pm.MongoClient(host='localhost',port=27017)
#Creating Database
v = client['vehicle']
#Creating Collection
cars = v['Cars']
#Insert a car document
d = {'companyName':'Tata','showroomprice':26.2,'onroadprice':28.5}
InsertID = cars.insert_one(d)
#Insert many car documents
li=[{'companyName':'Maruthi','showroomprice':12.4,'onroadprice':14.2},{'companyName':'BMW','showroomprice':30.2,'onroadprice':32.5}]
InsertID = cars.insert_many(li)
print("List of databases:")
print(client.list_database_names())
print("List of collections in Vehicle Database:")
print(v.list_collection_names())
#find all car documents
print("Documents in cars collection:")
for rec in cars.find():
print(rec)
#Connection Establishment
client = pm.MongoClient(host='localhost',port=27017)
#Creating Database
v = client['vehicle']
#Creating Collection
cars = v['Cars']
#Insert a car document
d = {'companyName':'Tata','showroomprice':26.2,'onroadprice':28.5}
InsertID = cars.insert_one(d)
#Insert many car documents
li=[{'companyName':'Maruthi','showroomprice':12.4,'onroadprice':14.2},{'companyName':'BMW','showroomprice':30.2,'onroadprice':32.5}]
InsertID = cars.insert_many(li)
print("List of databases:")
print(client.list_database_names())
print("List of collections in Vehicle Database:")
print(v.list_collection_names())
#find all car documents
print("Documents in cars collection:")
for rec in cars.find():
print(rec)
Output
List of databases:
['admin', 'config', 'local', 'vehicle']
List of collections in Vehicle Database:
['Cars']
Documents in cars collection:
{'_id': ObjectId('63aa8d246eaaa4c7040db40b'), 'companyName': 'Tata', 'showroomprice': 26.2, 'onroadprice': 28.5}
{'_id': ObjectId('63aa8db97a26373bc72c4b9b'), 'companyName': 'Maruthi', 'showroomprice': 12.4, 'onroadprice': 14.2}
{'_id': ObjectId('63aa8db97a26373bc72c4b9c'), 'companyName': 'BMW', 'showroomprice': 30.2, 'onroadprice': 32.5}
['admin', 'config', 'local', 'vehicle']
List of collections in Vehicle Database:
['Cars']
Documents in cars collection:
{'_id': ObjectId('63aa8d246eaaa4c7040db40b'), 'companyName': 'Tata', 'showroomprice': 26.2, 'onroadprice': 28.5}
{'_id': ObjectId('63aa8db97a26373bc72c4b9b'), 'companyName': 'Maruthi', 'showroomprice': 12.4, 'onroadprice': 14.2}
{'_id': ObjectId('63aa8db97a26373bc72c4b9c'), 'companyName': 'BMW', 'showroomprice': 30.2, 'onroadprice': 32.5}