Created
October 30, 2024 06:40
-
-
Save gonexwind/2010ec158858db140b13779964b47311 to your computer and use it in GitHub Desktop.
MongoDB CRUD with Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # python -m pip install "pymongo[srv]" | |
| from pymongo import MongoClient | |
| class Database: | |
| def __init__(self): | |
| # Connect to MongoDB | |
| self.client = MongoClient('mongodb_url') # MongoDB Url | |
| self.db = self.client['school'] # Database name | |
| self.collection = self.db['students'] # Collection name | |
| def insert(self, data): | |
| try: | |
| # Inserting the student data into the 'students' collection | |
| nim = self.collection.insert_one(data).inserted_id | |
| print(f"Data inserted with ID: {nim}") | |
| except Exception as e: | |
| print(f"Error: {e}") | |
| def fetch(self): | |
| try: | |
| # Retrieve all documents from the collection | |
| return self.collection.find() | |
| except Exception as e: | |
| print(f"Error: {e}") | |
| def update(self, nim, data): | |
| # Updating the student data in the 'students' collection | |
| self.collection.update_one({'nim': nim}, {"$set": data}) | |
| def delete(self, nim): | |
| # Deleting a student's data from the 'students' collection based on student ID | |
| self.collection.delete_one({'nim': nim}) | |
| # Create the database instance | |
| db = Database() | |
| # Create a student instance | |
| student = { | |
| 'nim': 1, | |
| 'username': 'fikky', | |
| 'email': '[email protected]', | |
| 'year': 2024, | |
| 'department': 'Computer Science' | |
| } | |
| # Insert the student into the database | |
| db.insert(student) | |
| # Fetch All Data | |
| def print_data(): | |
| students = db.fetch() | |
| for student in students: | |
| print(student) | |
| print_data() | |
| # Update | |
| student = { | |
| 'username': 'sasuke', | |
| 'hobbies': 'coding' | |
| } | |
| db.update(1, student) | |
| print_data() | |
| # Delete | |
| db.delete(1) | |
| print_data() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment