Skip to content

Instantly share code, notes, and snippets.

@shubhamnikam
Created August 15, 2021 18:39
Show Gist options
  • Save shubhamnikam/1312b24aad0cc0583020e7982f5cc365 to your computer and use it in GitHub Desktop.
Save shubhamnikam/1312b24aad0cc0583020e7982f5cc365 to your computer and use it in GitHub Desktop.
Python CRUD operation with mongodb
import pymongo
def get_db_connection():
db_client = pymongo.MongoClient("mongodb+srv://YOUR_USERNAME:YOUR_PWD@YOUR_SERVER/")
db_conn = db_client["test_db"]
db_coll = db_conn["products"]
return db_coll
def insert_one():
db_coll = get_db_connection()
data = {
'name': 'John Doe',
'rollNo': 1,
'age': 10,
'gender': 'M',
'address': {
'city': 'Pune',
'state': 'MH',
'country': 'IN'
}
}
x = db_coll.insert_one(data)
def insert_many():
db_coll = get_db_connection()
data = [
{
'name': 'John Doe',
'rollNo': 1,
'age': 10,
'gender': 'M'
},
{
'name': 'Jane Doe',
'rollNo': 2,
'age': 11,
'gender': 'F'
}
]
x = db_coll.insert_many(data)
def get_all():
db_coll = get_db_connection()
result = db_coll.find()
for item in result:
print(item)
def get_by_condition():
db_coll = get_db_connection()
result = db_coll.find_one({'name': 'John Doe'})
print(result)
def update_one():
db_coll = get_db_connection()
db_coll.update_one({'age': 10}, {"$set": {
'name': 'Mike Doe',
'rollNo': 1,
'age': 10,
'gender': 'M'
}}, upsert=False)
def delete():
db_coll = get_db_connection()
db_coll.delete_one({'age': 10})
if __name__ == '__main__':
# insert_one()
# insert_many()
get_all()
# get_by_condition()
# update_one()
# delete()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment