Using MongoDB with Python
Working with
MongoDb
A No-SQL database which works to manage data without need of SQL
statements
We need to install the MongoDb Software as a Service
sudo apt-get update
sudo apt-get install -y mongodb
Starting the MongoDB Service
sudo service mongodb start
Default is 27017
Stopping the MongoDb Service
sudo service mongodb stop
Install the package pymongo in conda
conda install pymongo
#Adding new recordimport pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["demodb"]
mycol = mydb["customer"]
cid=input("Enter customer id : ")
name=input("Enter Name : ")
email=input("Enter email : ")
c={ "cid": cid, "name": name, "email":email }
mycol.insert_one(c)
print("Record added")
# View all records
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["demodb"]
mycol = mydb["customer"]
for x in mycol.find():
print(x)
# Search specific record
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["demodb"]
mycol = mydb["customer"]
cid=input('Enter customer id : ')
query={'cid':cid}
result=mycol.find(query)
if result.count()==1:
print(result[0]['name'])
else:
print("Record not found")
# Update Record
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["demodb"]
mycol = mydb["customer"]
cid=input('Enter customer id : ')
query={'cid':cid}
result=mycol.find(query)
if result.count()==1:
print(result[0]['name'])
name=input("Enter new name : ")
myquery = { "cid": cid }
newvalues = { "$set": { "name": name} }
mycol.update_one(myquery,newvalues)
print("Record updated")
else:
print("Record not found")
# Delete a Record
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["demodb"]
mycol = mydb["customer"]
cid=input('Customer id to deleted : ')
myquery = { "cid": cid }
result=mycol.delete_one(myquery)
if(result.deleted_count==1):
print("Record has been deleted")
else:
print("Invalid Customer ID")
Comments
Post a Comment