Skip to content

Instantly share code, notes, and snippets.

@CodeWithHarry
Created April 17, 2022 12:46
Show Gist options
  • Save CodeWithHarry/958478c4cf55126c9259b0c2ef105bde to your computer and use it in GitHub Desktop.
Save CodeWithHarry/958478c4cf55126c9259b0c2ef105bde to your computer and use it in GitHub Desktop.
This gist contains the code written in PyMongo in one video by CodeWithHarry on YouTube - https://youtu.be/X3eSATZhXp0
import pymongo
connectionString = "mongodb+srv://username:[email protected]/test"
def insertDocument():
studentInfo = {
"name": "Drake",
"section": 2,
"maths_marks": 35,
"sst_marks": 79
}
student_id = collection.insert_one(studentInfo).inserted_id
print(f"Student with id {student_id} has been created")
def readDocuments():
# Inserting a Document
# Reading a Collection
# Using find function
myStudents = collection.find({"section": 1, "name": "Harry"})
# print(myStudents)
for student in myStudents:
print(student)
# Using findOne function
myStudent = collection.find_one({"section": 1})
print(myStudent)
def updateDocuments():
collection.update_one({"section": 1}, {'$inc': {'section': 100}})
collection.update_many({}, {'$inc': {'section': 100}})
def deleteDocuments():
r = collection.delete_one({"section": 101})
print(r.deleted_count)
r = collection.delete_many({})
print(r.deleted_count)
collection.update_many({})
if __name__ == '__main__':
client = pymongo.MongoClient(connectionString)
# Creating a Database for a School
db = client['wisdom-academy']
# Creating a Collection
collection = db.class1
# CRUD: Create, Read, Update, Delete
# 1. Create
# insertDocument()
# 2. Read
# readDocuments()
# 3. Update
# updateDocuments()
# 4. Delete
# deleteDocuments()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment