python --version
pip install pymongo
mongosh --version
Connect to MongoDB, perform document operations, build an aggregation pipeline, and create indexes for performance.
1 from pymongo import MongoClient, ASCENDING, DESCENDING 2 from pymongo.errors import DuplicateKeyError 3 from datetime import datetime, timedelta 4 import random 5 6 client = MongoClient("mongodb://localhost:27017/") 7 db = client["learn_db"] 8 orders = db["orders"] 9 10 # Drop and recreate for clean demo 11 orders.drop() 12 13 # Insert sample data 14 categories = ["Electronics", "Clothing", "Books"] 15 docs = [ 16 { 17 "orderId": f"ORD-{i:04d}", 18 "customerId": f"CUST-{random.randint(1, 5)}", 19 "category": random.choice(categories), 20 "amount": round(random.uniform(10, 500), 2), 21 "createdAt": datetime.utcnow() - timedelta(days=random.randint(0, 30)), 22 "status": random.choice(["pending", "shipped", "delivered"]), 23 } 24 for i in range(1, 21) 25 ] 26 result = orders.insert_many(docs) 27 print(f"Inserted {len(result.inserted_ids)} orders") 28 29 # Query with operators 30 high_value = list(orders.find( 31 {"amount": {"$gt": 200}, "status": {"$in": ["shipped", "delivered"]}}, 32 {"orderId": 1, "amount": 1, "status": 1, "_id": 0}, # projection 33 )) 34 print(f"High-value delivered/shipped orders: {len(high_value)}") 35 36 # Update 37 update_result = orders.update_many( 38 {"status": "pending", "amount": {"$lt": 50}}, 39 {"$set": {"status": "cancelled"}, "$currentDate": {"updatedAt": True}}, 40 ) 41 print(f"Cancelled {update_result.modified_count} small pending orders") 42 43 # Aggregation pipeline 44 pipeline = [ 45 {"$match": {"status": {"$ne": "cancelled"}}}, 46 {"$group": { 47 "_id": "$category", 48 "totalRevenue": {"$sum": "$amount"}, 49 "orderCount": {"$sum": 1}, 50 "avgOrder": {"$avg": "$amount"}, 51 }}, 52 {"$sort": {"totalRevenue": -1}}, 53 {"$project": { 54 "category": "$_id", 55 "totalRevenue": {"$round": ["$totalRevenue", 2]}, 56 "orderCount": 1, 57 "avgOrder": {"$round": ["$avgOrder", 2]}, 58 "_id": 0, 59 }}, 60 ] 61 for row in orders.aggregate(pipeline): 62 print(row) 63 64 # Index creation 65 orders.create_index([("customerId", ASCENDING), ("createdAt", DESCENDING)], name="cust_date_idx") 66 print("Index created") 67 68 # Explain query plan 69 explanation = orders.find({"customerId": "CUST-1"}).sort("createdAt", -1).explain() 70 winning_plan = explanation["queryPlanner"]["winningPlan"] 71 print(f"Winning plan stage: {winning_plan.get('stage')}") 72
Sign in to share your feedback and join the discussion.