Hey there, fellow developer! Ready to dive into the world of MongoDB and Python? Great, because we're about to build a robust API integration that'll make your data handling a breeze. MongoDB's flexibility and Python's simplicity are a match made in heaven, so let's get started!
Before we jump in, make sure you've got:
First things first, let's get connected:
pip install pymongo
Now, let's establish that connection:
from pymongo import MongoClient client = MongoClient('mongodb://localhost:27017/') db = client['your_database'] collection = db['your_collection']
Easy peasy, right? You're now connected and ready to roll!
CRUD - the bread and butter of any database operation. Let's break it down:
# Insert one document collection.insert_one({"name": "John", "age": 30}) # Insert multiple documents collection.insert_many([ {"name": "Alice", "age": 25}, {"name": "Bob", "age": 35} ])
# Find one document print(collection.find_one({"name": "John"})) # Find multiple documents for doc in collection.find({"age": {"$gt": 25}}): print(doc)
# Update one document collection.update_one({"name": "John"}, {"$set": {"age": 31}}) # Update multiple documents collection.update_many({"age": {"$lt": 30}}, {"$inc": {"age": 1}})
# Delete one document collection.delete_one({"name": "John"}) # Delete multiple documents collection.delete_many({"age": {"$gt": 40}})
Time to flex those querying muscles:
# Filtering and sorting results = collection.find({"age": {"$gt": 25}}).sort("name", 1).limit(5) # Aggregation pipeline pipeline = [ {"$match": {"age": {"$gt": 25}}}, {"$group": {"_id": "$name", "avg_age": {"$avg": "$age"}}} ] results = collection.aggregate(pipeline)
Speed up your queries with indexes:
# Create an index collection.create_index([("name", 1)]) # Explain a query explanation = collection.find({"name": "John"}).explain() print(explanation)
Always be prepared:
try: result = collection.insert_one({"name": "Error Test"}) except pymongo.errors.PyMongoError as e: print(f"An error occurred: {e}") # Use connection pooling (pymongo handles this automatically) # Perform bulk operations for better performance bulk_ops = [ InsertOne({"name": "Bulk1"}), UpdateOne({"name": "John"}, {"$set": {"age": 32}}), DeleteOne({"name": "Alice"}) ] collection.bulk_write(bulk_ops)
Let's wrap it up nicely:
class MongoDBAPI: def __init__(self, db_name, collection_name): self.client = MongoClient('mongodb://localhost:27017/') self.db = self.client[db_name] self.collection = self.db[collection_name] def insert(self, document): return self.collection.insert_one(document) def find(self, query): return self.collection.find(query) # Add more methods as needed
Don't forget to test:
import pytest from unittest.mock import Mock, patch @pytest.fixture def mongo_api(): return MongoDBAPI('test_db', 'test_collection') @patch('your_module.MongoClient') def test_insert(mock_client, mongo_api): mock_collection = Mock() mock_client.return_value.__getitem__.return_value.__getitem__.return_value = mock_collection mongo_api.insert({"test": "data"}) mock_collection.insert_one.assert_called_once_with({"test": "data"})
And there you have it! You've just built a solid MongoDB API integration in Python. Remember, this is just the beginning - there's so much more you can do with MongoDB and Python. Keep exploring, keep coding, and most importantly, have fun with it!
For more advanced topics, check out the official MongoDB Python driver documentation and the MongoDB Manual. Happy coding!