Claude Code के साथ NoSQL/MongoDB: स्कीमा, इंडेक्स और Aggregation
Claude Code से MongoDB: access patterns, validation, indexes, aggregation, tests और rollout checklist।
पहले access pattern, फिर collection
NoSQL/MongoDB ऐसा database है जो डेटा को fixed rows और columns वाली table में बंद नहीं करता। MongoDB डेटा को JSON जैसे documents के रूप में store करता है। इसलिए सही design इस बात से तय होता है कि application कौन सा data साथ में पढ़ती है, कैसे sort करती है, कौन से fields update होते हैं और कौन सी reporting चाहिए।
Claude Code से अच्छा MongoDB design पाने के लिए सिर्फ “orders schema बना दो” कहना काफी नहीं है। Screens, API response, update frequency, expected data volume, reporting और permission rules भी बताएं। तब Claude Code embedding बनाम reference, indexes, aggregation pipeline, validation schema, seed/test और rollout risks पर सही review दे सकता है।
Practical use cases
| Use case | Common reads | MongoDB model | Risk |
|---|---|---|---|
| E-commerce orders | user के recent orders, order detail, monthly revenue | खरीदे गए product name और price को order में embed करें, productId रखें | product change से पुराना order गलत बदलना |
| SaaS audit logs | organization, user, date range, event type | append-only documents, compound indexes, जरूरत हो तो TTL | बड़े collection पर slow scan |
| CMS articles | slug से article, status और category list | slug, status, publish date indexes | drafts या internal notes leak होना |
| Support tickets | customer queue, assigned agent, recent comments | limited comments embed करें, attachments अलग रखें | arrays का बिना सीमा बढ़ना |
अगर आप relational model से तुलना कर रहे हैं, तो Claude Code database design, API development, Prisma ORM और SQL optimization भी देखें।
Claude Code के लिए बेहतर prompt
You are the MongoDB design reviewer for this project.
Design from access patterns before proposing collections.
Requirements:
- Users view their recent orders in reverse chronological order.
- Order detail shows product name, price, and category at purchase time.
- Product price changes must not rewrite historical orders.
- Admins need revenue by month, status, and category.
- Use transactions only when partial success would break business correctness.
- Include validation schema, indexes, seed data, aggregation, explain checks, and rollout checklist.
अच्छा जवाब साफ बताएगा कि कौन सा data embed होगा और कौन सा reference रहेगा। Order में product name, purchase price और category उस समय की business fact हैं, इसलिए उन्हें order document में रखना सही है। Current stock, product description और catalog rules product document में रहेंगे और productId से जुड़ेंगे।
Copy-paste runnable demo
Local MongoDB चलाएं:
docker run --name mongo-claude-demo -p 27017:27017 -d mongo:8
Official Node.js driver install करें:
npm init -y
npm install mongodb
npm install -D tsx typescript
mkdir -p src
src/mongodb-workflow.ts बनाएं:
import { MongoClient, ObjectId } from "mongodb";
const client = new MongoClient(process.env.MONGODB_URI ?? "mongodb://localhost:27017");
async function main() {
await client.connect();
const db = client.db("claude_code_shop_hi");
await db.dropDatabase();
await db.createCollection("orders", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["userId", "status", "items", "totalAmount", "createdAt", "updatedAt"],
properties: {
userId: { bsonType: "objectId" },
status: { enum: ["pending", "paid", "shipped", "cancelled"] },
totalAmount: { bsonType: ["int", "long", "double", "decimal"], minimum: 0 },
createdAt: { bsonType: "date" },
updatedAt: { bsonType: "date" },
items: {
bsonType: "array",
minItems: 1,
items: {
bsonType: "object",
required: ["productId", "name", "category", "price", "quantity"],
properties: {
productId: { bsonType: "objectId" },
name: { bsonType: "string" },
category: { bsonType: "string" },
price: { bsonType: ["int", "long", "double", "decimal"], minimum: 0 },
quantity: { bsonType: "int", minimum: 1 }
}
}
}
}
}
}
});
const products = db.collection("products");
const orders = db.collection("orders");
await Promise.all([
orders.createIndex({ userId: 1, createdAt: -1 }, { name: "orders_by_user_recent" }),
orders.createIndex({ status: 1, createdAt: -1 }, { name: "orders_by_status_recent" }),
orders.createIndex({ "items.category": 1, createdAt: -1 }, { name: "orders_by_category_month" })
]);
const inserted = await products.insertMany([
{ name: "Claude Code Workshop", category: "training", currentPrice: 48000 },
{ name: "MongoDB Review Template", category: "template", currentPrice: 9800 }
]);
const userId = new ObjectId();
const now = new Date("2026-06-01T09:00:00.000Z");
await orders.insertOne({
userId,
status: "paid",
items: [
{ productId: inserted.insertedIds[0], name: "Claude Code Workshop", category: "training", price: 48000, quantity: 1 },
{ productId: inserted.insertedIds[1], name: "MongoDB Review Template", category: "template", price: 9800, quantity: 2 }
],
totalAmount: 67600,
createdAt: now,
updatedAt: now
});
const report = await orders.aggregate([
{ $match: { status: { $in: ["paid", "shipped"] } } },
{ $unwind: "$items" },
{
$group: {
_id: {
month: { $dateToString: { format: "%Y-%m", date: "$createdAt" } },
category: "$items.category"
},
revenue: { $sum: { $multiply: ["$items.price", "$items.quantity"] } },
quantity: { $sum: "$items.quantity" }
}
},
{ $sort: { "_id.month": 1, revenue: -1 } }
]).toArray();
const explain = await orders.find({ userId }).sort({ createdAt: -1 }).limit(10).explain("executionStats");
if (report.length !== 2) throw new Error("aggregation failed");
if ((explain.executionStats?.totalDocsExamined ?? 0) > 1) throw new Error("index check failed");
console.log(JSON.stringify({ report, examined: explain.executionStats.totalDocsExamined }, null, 2));
}
main()
.catch((error) => {
console.error(error);
process.exitCode = 1;
})
.finally(async () => {
await client.close();
});
Run करें:
npx tsx src/mongodb-workflow.ts
यह demo validation schema, indexes, seed data, aggregation pipeline और explain check दिखाता है। Output को Claude Code में paste करके पूछें कि query, sort और index order सही हैं या नहीं।
Embedding या reference
Embedding तब अच्छा है जब data हमेशा साथ पढ़ा जाता है और किसी समय की fact को सुरक्षित रखना होता है। Reference तब बेहतर है जब data स्वतंत्र रूप से बदलता है, बिना सीमा बढ़ सकता है, या single source of truth होना चाहिए। Order में purchased item snapshot embed करें, लेकिन product catalog को reference रखें। Audit logs, notifications और long comment history parent document में अनंत तक नहीं बढ़ने चाहिए।
Indexes, aggregation और transactions
Indexes real queries से निकाले जाते हैं। find({ userId }).sort({ createdAt: -1 }) के लिए { userId: 1, createdAt: -1 } सही है। Aggregation में पहले $match से data कम करें, फिर जरूरत हो तो $unwind, फिर $group करें। Heavy dashboards के लिए cache या pre-aggregated collection ज्यादा स्थिर हो सकते हैं।
Transactions तभी उपयोग करें जब partial success business को गलत बना दे, जैसे order को paid करना और payment record लिखना। Notifications, search index sync और counters अक्सर retry हो सकते हैं।
Official references: Data Modeling, Indexes, Aggregation, Transactions और MongoDB Node.js Driver।
Common pitfalls
पहला pitfall है relational normalization को बिना सोचे copy करना। दूसरा है comments, logs, notifications जैसे unlimited arrays को embed करते जाना। तीसरा है सिर्फ TypeScript types पर भरोसा करके database validation छोड़ देना। चौथा है index बनाने के बाद explain("executionStats") न देखना। पांचवां है हर API request पर heavy aggregation चलाना।
Production से पहले check करें कि मुख्य queries के indexes हैं, validation schema लागू है, seed/test list, detail और report flows cover करते हैं, explain में unexpected full scan नहीं है, transactions की boundary साफ है, और backup/rollback process लिखा हुआ है।
ClaudeCodeLab टीमों को Claude Code training, CLAUDE.md templates और MongoDB/API implementation consultation में मदद कर सकता है। इस workflow को आजमाने पर सबसे ज्यादा फायदा explain output को Claude Code से review कराने में मिला, क्योंकि कई बार नया index जोड़ने से पहले query shape सुधारना बेहतर होता है।
मुफ़्त PDF: Claude Code cheatsheet
Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.
हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.
लेखक के बारे में
Masa
Claude Code workflow और team adoption पर काम करने वाला engineer.
संबंधित लेख
Claude Code Obsidian to CLAUDE.md workflow: context बार-बार न समझाएं
Obsidian notes को CLAUDE.md operating notes में बदलकर Claude Code sessions को resume करना आसान बनाएं.
Claude Code Revenue CTA Routing: article से PDF, Gumroad और consultation तक
Reader intent के आधार पर free PDF, Gumroad products और consultation तक CTA route करने वाला workflow.
Claude Code टीम हैंडऑफ नियम: review proof, permissions, rollback और revenue path
Claude Code टीम काम के लिए evidence, permission rules, rollback, free PDF, Gumroad और consultation path वाला handoff.