Use Cases (अपडेट: 1/6/2026)

Claude Code के साथ NoSQL/MongoDB: स्कीमा, इंडेक्स और Aggregation

Claude Code से MongoDB: access patterns, validation, indexes, aggregation, tests और rollout checklist।

Claude Code के साथ NoSQL/MongoDB: स्कीमा, इंडेक्स और Aggregation

पहले 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 caseCommon readsMongoDB modelRisk
E-commerce ordersuser के recent orders, order detail, monthly revenueखरीदे गए product name और price को order में embed करें, productId रखेंproduct change से पुराना order गलत बदलना
SaaS audit logsorganization, user, date range, event typeappend-only documents, compound indexes, जरूरत हो तो TTLबड़े collection पर slow scan
CMS articlesslug से article, status और category listslug, status, publish date indexesdrafts या internal notes leak होना
Support ticketscustomer queue, assigned agent, recent commentslimited 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 सुधारना बेहतर होता है।

#Claude Code #MongoDB #NoSQL #database #backend
मुफ़्त

मुफ़्त PDF: Claude Code cheatsheet

Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.

हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.

Masa

लेखक के बारे में

Masa

Claude Code workflow और team adoption पर काम करने वाला engineer.