I gave Claude code control of a live MongoDB app (without breaking it)
Handing an AI agent control of a real application sounds terrifying. But with the right guardrails, it can become a powerful way to modernize your stack without losing control. In this guide, we’ll walk through how Claude was given code-level and database-level access to a production-like MongoDB app, redesigned the customer data model, migrated tens of thousands of records, refactored the code, and proved nothing broke.
What this setup is trying to solve
Imagine you’re on the platform team for a large e‑commerce marketplace. Over time, your customer data has drifted into a mess:
• Customer profiles are split across multiple MongoDB collections.
• Imports have created inconsistent names and email formats.
• Old business rules left behind unsupported statuses like “VIP customer”.
The application still works, but the original customer model no longer matches how the product is used. You now need a cleaner “customer 360” view where identity, address, communication preferences, and an order summary live together in a single, coherent profile.
The challenge: migrate this legacy model to a new schema, fix all the edge cases, keep the app running, and prove that no data was lost or corrupted.
Claude, MongoDB agent skills, and MCP: who does what?
This workflow combines three key pieces:
Claude Code
Claude is the reasoning engine. It plans the migration, designs the schema, writes queries and refactors, and explains each step. But it doesn’t get blind, unlimited access.
MongoDB agent skills
These are specialized skills that give Claude MongoDB-specific engineering guidance. Think of them as a playbook for:
• Schema design best practices
• Query optimization
• Indexing strategies
• Migration patterns
MongoDB MCP server
The MCP (Model Context Protocol) server is how Claude interacts with the real database. It provides controlled tools to:
• Inspect schemas, indexes, counts, and sample documents
• Run aggregations and lookups
• Perform writes (only when explicitly enabled)
If the skills are the playbook, MCP is the eyes and hands. Claude coordinates the workflow, but the human still approves consequential steps and can roll back safely. For a broader look at building safe coding workflows with AI, see this complete workflow for AI-assisted coding without losing control.
Setting up MongoDB skills and MCP
To get started, two components are installed locally:
• The MongoDB agent skills package
• The MongoDB MCP server
You can install the skills via a slash command inside Claude Code or by running an npx command that adds the MongoDB agent skills to your environment. The MCP server is configured by adding your MongoDB connection string to the MCP config file.
In this walkthrough, a local MCP server is used for an isolated, repeatable environment. MongoDB has since released an Atlas-managed MCP server, which is a fully hosted option that connects coding agents to Atlas without teams having to run the server themselves.
Inspecting the legacy data model safely
Before any writes are allowed, the MCP server is run in read-only mode. In this phase, Claude can:
• Inspect collections and schemas
• Check indexes
• Count documents
• Sample and analyze records
The demo dataset recreates a realistic marketplace scenario:
• ~10,000 customer documents
• 10,000 address documents
• 10,000 preference documents
• Just under 50,000 orders
The legacy model spreads customer data across three collections (customers, addresses, preferences), while the app also queries orders separately. Claude uses the schema design skill to analyze both sides of the problem:
• What’s stored in MongoDB
• How the application actually reads and combines that data
This second part is crucial. A good MongoDB schema should reflect real access patterns, not just collection names.
Designing the new customer 360 schema
Based on the access patterns, Claude proposes a new Customer v2 document model:
• Keep the original customer _id for continuity
• Add an explicit schemaVersion field
• Group name and contact info into clear sub-objects
• Embed address and preferences directly in the customer document
• Store a computed order summary (e.g., total orders, last order date)
• Keep full order history in its own collection, referenced from customers
This balances the trade-off between embedding and referencing: bounded profile data that’s always read together is embedded, while unbounded order history remains separate.
The plan also defines strict migration rules and invariants:
• Source and target customer counts must match
• IDs must be identical between versions
• No duplicate customer numbers
• Only allowed status values in the new model
• Emails normalized (e.g., lowercase, trimmed whitespace)
• All 24 seeded edge-case warnings preserved, not silently dropped
• Required indexes created for new access patterns
Handling messy legacy edge cases
The dataset includes 24 deliberately seeded legacy edge cases, such as:
• Uppercase or oddly spaced email addresses
• Inconsistent name spacing
• An old status value like VIP customer that the new model doesn’t recognize
A naive migration might “clean” these by dropping or overwriting problematic fields, which would lose real information. Instead, Claude’s plan ensures:
• Emails are normalized but still traceable to their original values
• Unsupported statuses are handled explicitly rather than erased
• All other customer data remains unchanged compared to non-edge documents
The MCP server surfaces these edge records so they can be reviewed and verified after migration.
Enabling controlled write access
Once the migration plan looks solid, write access is enabled in a tightly scoped way. A command is issued that:
• Allows only create and update operations in the isolated demo database
• Keeps delete tools disabled
• Keeps Atlas administration tools disabled
Claude now has the ability to write, but under strict conditions:
• It must explain each write operation in detail
• It must wait for explicit human approval before executing
This staged access model is key: the source state remains immutable, and the cutover is controlled from the application side. If anything goes wrong, the app can simply be pointed back to the legacy collections.
Running a server-side migration with aggregations
Instead of streaming tens of thousands of documents through the model and rewriting them one by one, Claude builds a MongoDB aggregation pipeline that:
• Joins customers, addresses, and preferences on the server
• Applies transformations and normalization rules
• Computes the order summary
• Writes the result into the new customers_v2 collection via $merge
This approach is important:
• Claude plans and orchestrates the logic
• MongoDB executes the heavy data work inside the deployment
After approval, the aggregation runs and populates the new collection. The initial check confirms:
• 10,000 documents in the new customers_v2 collection
• Legacy collections remain untouched
Matching counts alone aren’t enough, though, so deeper validation comes next.
Refactoring the application to use the new schema
The database migration is only half the story. The application still expects the legacy model. To complete the transition, Claude is asked to refactor the customer repository layer without changing the API contract used by the dashboard.
The core change is simple but meaningful:
• Previously: the repository fetched customers, addresses, preferences, and orders separately, then stitched them together at request time.
• Now: it reads from the customers_v2 document, which already contains the embedded profile and order summary, and returns the same response shape to the UI.
Once this refactor is applied, the app switches to schema version 2 while still showing 10,000 customers. The difference is that each bounded customer profile is now a single coherent document, and the 24 edge-case warnings are preserved instead of hidden.
If you’re interested in how Claude performs on broader real-world coding tasks and design work, you may also like this comparison of ChatGPT vs Claude for coding and UI design.
Verifying that nothing broke
To treat this as a real migration, the final step is independent validation. Claude and the MongoDB MCP tools are used to check:
• Source vs target customer counts (10,000 vs 10,000)
• Missing IDs (should be zero)
• Duplicate customer numbers (should be zero)
• All 24 edge-case warnings preserved
• Application still functioning correctly against customers_v2
Only after these invariants pass can the migration be considered successful.
Measuring query behavior and performance
Finally, the official query optimizer agent skill is used with the MCP server to inspect real queries against the new schema. For example, Claude can:
• Check that lookups by contact email are using the intended index
• Show the query plan and confirm index usage
• Avoid making unsubstantiated claims about speedups
Instead of promising a dramatic performance boost, the workflow focuses on verifiable evidence: which indexes are used, whether new ones are needed, and how the new access patterns behave in practice.
Why this AI-driven workflow works safely
This migration worked not because Claude had unrestricted control, but because it didn’t. The safety model looked like this:
• Read-only first: Claude investigates the existing database and application behavior without any ability to write or delete.
• Explicit planning: A detailed migration plan and target schema are generated and reviewed by a human.
• Staged write access: Only specific write operations are enabled, with delete and admin tools disabled.
• Human approvals: Every consequential operation requires explanation and explicit approval.
• Immutable source state: Legacy collections remain unchanged; rollback is just pointing the app back.
• Independent validation: Counts, IDs, edge cases, and app behavior are all checked after migration.
MongoDB’s agent skills provide the domain knowledge for good schema and query decisions, while the MCP server connects Claude’s reasoning to a real deployment in a controlled way. The result is a workflow where AI can move from giving advice to performing real, auditable actions—without giving up human control.
Key takeaways for your own AI-powered migrations
If you’re considering using AI agents to touch your database or application code, this example suggests a few best practices:
• Start in an isolated environment that mirrors production.
• Use read-only access first to let the model understand your real access patterns.
• Require a written migration plan and schema proposal before enabling writes.
• Use server-side operations (like MongoDB aggregations) for bulk work, orchestrated by the model.
• Keep legacy data immutable and make cutover an application-level switch.
• Validate everything with clear invariants before declaring success.
With the right tools and guardrails, AI agents like Claude can safely help redesign schemas, migrate data, and refactor code—turning complex, risky projects into structured, verifiable workflows.
Comments
No comments yet. Be the first to share your thoughts!