Skip to content

Instantly share code, notes, and snippets.

@ferdhika31
Created March 27, 2017 13:46
Show Gist options
  • Save ferdhika31/c0050be67dfab1c441df8804f2717b66 to your computer and use it in GitHub Desktop.
Save ferdhika31/c0050be67dfab1c441df8804f2717b66 to your computer and use it in GitHub Desktop.
CRUD PyMongo at command line/terminal
# Source From : https://github.com/jay3dec/CRUD_Python_MongoDb/blob/master/MongoDbCRUD.py
# Python Version : 3
# Install pymongo : pip3 install pymongo
from pymongo import MongoClient
# creating connectioons for communicating with Mongo DB
client = MongoClient('localhost:27017')
db = client.EmployeeData
def main():
while(1):
# chossing option to do CRUD operations
selection = input('\nSelect 1 to insert, 2 to update, 3 to read, 4 to delete\n')
if selection == '1':
insert()
elif selection == '2':
update()
elif selection == '3':
read()
elif selection == '4':
print ('delete')
delete()
else:
print ('\n INVALID SELECTION \n')
# Function to insert data into mongo db
def insert():
try:
employeeId = input('Enter Employee id :')
employeeName = input('Enter Name :')
employeeAge = input('Enter age :')
employeeCountry = input('Enter Country :')
db.Employees.insert_one(
{
"id" : employeeId,
"name" : employeeName,
"age" : employeeAge,
"country" : employeeCountry
})
print ('\nInserted data successfully\n')
except (Exception, e):
print (str(e))
# Function to update record to mongo db
def update():
try:
criteria = input('\nEnter id to update\n')
name = input('\nEnter name to update\n')
age = input('\nEnter age to update\n')
country = input('\nEnter country to update\n')
db.Employees.update_one(
{"id": criteria},
{
"$set": {
"name":name,
"age":age,
"country":country
}
}
)
print ("\nRecords updated successfully\n")
except(Exception, e):
print (str(e))
# function to read records from mongo db
def read():
try:
empCol = db.Employees.find()
print ('\n All data from EmployeeData Database \n')
for emp in empCol:
print (emp)
except (Exception, e):
print (str(e))
# Function to delete record from mongo db
def delete():
try:
criteria = input('\nEnter employee id to delete\n')
db.Employees.delete_many({"id":criteria})
print ('\nDeletion successful\n')
except (Exception, e):
print (str(e))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment