MongoDB drivers.
PyMongo (sync)
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
db = client.myapp
users = db.users
users.insert_one({"name": "Alice"})
list(users.find({"age": {"$gt": 25}}))
users.update_one({"name": "Alice"}, {"$set": {"age": 31}})
users.delete_one({"_id": ...})
users.create_index([("email", 1)], unique=True)
client.close()
Motor (async)
from motor.motor_asyncio import AsyncIOMotorClient
client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client.myapp
await db.users.insert_one({"name": "Alice"})
async for u in db.users.find({"active": True}):
print(u)
await client.close()
Connection pooling
client = MongoClient(uri, maxPoolSize=100, minPoolSize=10)
Reuse client across requests.
Bulk write
from pymongo import InsertOne, UpdateOne, DeleteOne
users.bulk_write([
InsertOne({"name": "A"}),
UpdateOne({"name": "B"}, {"$set": {"age": 30}}),
DeleteOne({"_id": ...}),
], ordered=False)
Aggregation
list(db.orders.aggregate([
{"$match": {"status": "completed"}},
{"$group": {"_id": "$user_id", "total": {"$sum": "$amount"}}},
]))
Transactions
with client.start_session() as s:
with s.start_transaction():
db.accounts.update_one({"_id": a}, {"$inc": {"bal": -100}}, session=s)
db.accounts.update_one({"_id": b}, {"$inc": {"bal": 100}}, session=s)
Pydantic (validation)
from pydantic import BaseModel, Field
from bson import ObjectId
class User(BaseModel):
id: ObjectId = Field(alias="_id")
name: str
email: str
class Config:
arbitrary_types_allowed = True
json_encoders = {ObjectId: str}
doc = users.find_one({...})
user = User.model_validate(doc)
Beanie (async ODM)
from beanie import Document, init_beanie
class User(Document):
name: str
email: str
class Settings:
name = "users"
await init_beanie(database=db, document_models=[User])
await User(name="Alice", email="[email protected]").insert()
user = await User.find_one(User.email == "[email protected]")
Pydantic-based ODM.
Node.js native
import { MongoClient, ObjectId } from "mongodb";
const client = new MongoClient("mongodb://localhost:27017");
await client.connect();
const db = client.db("myapp");
const users = db.collection("users");
await users.insertOne({ name: "Alice" });
const u = await users.findOne({ _id: new ObjectId("...") });
await users.updateOne({ _id }, { $set: { age: 31 } });
await client.close();
Mongoose (Node ODM)
npm i mongoose
import mongoose from "mongoose";
await mongoose.connect("mongodb://localhost:27017/myapp");
const UserSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, unique: true },
age: Number,
}, { timestamps: true });
const User = mongoose.model("User", UserSchema);
await User.create({ name: "Alice", email: "[email protected]" });
const user = await User.findOne({ email: "[email protected]" });
await User.updateOne({ _id }, { age: 31 });
Index in schema
UserSchema.index({ email: 1 }, { unique: true });
UserSchema.index({ name: "text" });
Hooks
UserSchema.pre("save", function (next) {
this.updated = new Date();
next();
});
UserSchema.post("save", function (doc) {
notify(doc);
});
Populate (join)
const PostSchema = new Schema({
title: String,
author: { type: Schema.Types.ObjectId, ref: "User" },
});
const post = await Post.findById(id).populate("author");
Server-side $lookup behind the scenes.
Cursor
const cursor = users.find({});
for await (const u of cursor) {
console.log(u);
}
Type-safe TS
interface User { _id: ObjectId; name: string; email: string; }
const users = db.collection<User>("users");
await users.insertOne({ name: "A", email: "a@b" }); // typed
Common mistakes
- New client per request → connection storm.
- Sync driver in async framework → blocks event loop.
- Mongoose schema not matching actual data.
- Missing
await(silently un-resolved promise). - ObjectId vs string comparison fails.
Read this next
If you want my Mongo client wrappers, they’re at rajpoot.dev .
Building something AI-, backend-, or data-heavy and want a second pair of eyes? I do consulting and freelance work — see my projects and ways to reach me at rajpoot.dev .