For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
MongoDB MCP Server Usage Examples
This page demonstrates how to use the MongoDB MCP Server through practical examples with natural language prompts. Each example shows the prompt you can enter in your AI client and an example response you might receive from the large language model (LLM).
You can use the examples on this page as starting points for your own interactions with the MongoDB MCP Server.
Note
The exact output you receive will vary depending on your data, AI client, and the LLM you're using. Private information such as organization IDs, project IDs, and passwords are redacted in these examples.
Prerequisites
Before running these examples, ensure that you have the following:
The following examples demonstrate how to manage your Atlas infrastructure by using the MongoDB MCP Server.
View Organizations and Projects
Get an overview of your Atlas account structure and available resources.
Show my Atlas organizations and projects
Ran ``atlas-list-orgs``Ran ``atlas-list-projects``Here are your MongoDB Atlas organizations and projects:**Organizations:**TestOrganizationOrganization ID: XXX**Projects:**TestProjectProject ID: XXXOrganization: TestOrganizationCreated: August 7, 2020 at 11:48:55 AMYou have one organization containing one project. Thisproject contains your TestCluster that we're currentlyconnected to.
Create an Atlas Cluster
Set up a new Atlas project with a cluster and all necessary access configurations in a single workflow.
Create a new Atlas project named myNewProject and create afree cluster named myNewCluster in the new project, addaccess list for my current IP, create a database user namedmyNewUser with read and write access to the new cluster, andreturn the connection string for the new cluster
I'll create a new Atlas project, free cluster, and set upall the necessary access details for you.Ran ``atlas-create-project``Great! I've created a new project named "myNewProject"in your MongoDB Atlas organization. Now let's list theprojects to get the project ID for the new project:Ran ``atlas-list-projects``Now I'll create a free cluster named "myNewCluster" in thenew project:Ran ``atlas-create-free-cluster``Now, I'll add your current IP address to the access list:Ran ``atlas-create-access-list``Now let's create a database user named "myNewUser" with readand write access:Ran ``atlas-create-db-user``Perfect! Everything has been set up successfully:**New Project Information:**Project Name: myNewProjectProject ID: XXX**New Cluster Information:**Cluster Name: myNewClusterRegion: US East (US_EAST_1)**Database User:**Username: myNewUserPassword: XXXAccess: Read and write to any database**Connection String:**mongodb+srv://myNewUser:XXX@myNewCluster.mongodb.net/Your current IP address has been added to the access list,so you should be able to connect to the cluster from yourcurrent location. The cluster will take a few minutes tofully provision and be ready for connections.
List Supported Atlas Regions
To look up the region codes and human-readable locations that Atlas supports for a cloud provider use atlas-get-regions. This is useful for resolving a natural-language location, such as "Iowa" or "Northern Europe", to the exact region code that tools like atlas-create-cluster and atlas-upgrade-cluster expect.
What Atlas regions are available on GCP?
Ran ``atlas-get-regions``Here are some of the supported Atlas regions on GCP:CENTRAL_US — Iowa, USAUS_EAST_4 — Northern Virginia, USAWESTERN_EUROPE — BelgiumEUROPE_WEST_3 — Frankfurt, GermanyEUROPE_NORTH_1 — FinlandASIA_SOUTH_1 — Mumbai, IndiaAUSTRALIA_SOUTHEAST_1 — Sydney, AustraliaLet me know if you'd like the full list or regions foranother provider.
Create a Dedicated Atlas Cluster
Use atlas-create-cluster to create a dedicated Atlas cluster with M10–M80 instance sizes. To create a free-tier cluster instead, use atlas-create-free-cluster.
The tool requires projectId, clusterName, provider, and regions.
Create a dedicated Atlas cluster named myDedicatedClusterin project myProject on AWS in US East
I'll create a dedicated Atlas cluster on AWSin US_EAST_1.Ran ``atlas-create-cluster``Cluster creation is underway. Here's a summary:**Cluster Details:**Name: myDedicatedClusterProject ID: XXXProvider: AWSRegions: US_EAST_1Instance Size: M10Cluster Type: Replica SetMongoDB Version: LatestBackup: SnapshotCompute Autoscaling: Enabled (M10–M30)Disk Autoscaling: EnabledThe cluster is now being provisioned — it will takea few minutes to reach IDLE state. You can use``atlas-inspect-cluster`` to poll its status,or connection strings will be available once it's ready.
Non-Default Options
To specify a non-default cluster type, instance size, or backup settings, include those options in your prompt:
Create a dedicated Atlas cluster named myShardedClusterin project myProject on AWS in US East with cluster typeSHARDED, instance size M30, and continuous backups enabled
I'll create a dedicated sharded Atlas clusteron AWS in US_EAST_1.Ran ``atlas-create-cluster``Cluster creation initiated successfully. Here'sa summary:**Cluster Details:**Name: myShardedClusterProject ID: XXXProvider: AWSRegions: US_EAST_1Cluster Type: ShardedInstance Size: M30Backup: Continuous (point-in-time restore)Compute Autoscaling: Enabled (M30–M50)Disk Autoscaling: EnabledThe cluster is now being provisioned — it typicallytakes a few minutes to reach IDLE state.You can use ``atlas-inspect-cluster`` to poll its readiness,and connection strings will be available once it's IDLE.
Multiple Regions
To distribute a cluster across multiple regions, name up to three regions in your prompt. The tool treats the regions as an ordered list: the first region has the highest priority and holds the primary node. The tool distributes electable nodes as three nodes in one region, two and one node across two regions, or two, two, and one node across three regions.
Create a dedicated Atlas cluster named myMultiRegionClusterin project myProject on AWS across US East, Ohio, and Ireland
I'll create a dedicated Atlas cluster on AWS acrossUS_EAST_1, US_EAST_2, and EU_WEST_1.Ran ``atlas-create-cluster``Cluster creation is underway. Here's a summary:**Cluster Details:**Name: myMultiRegionClusterProject ID: XXXProvider: AWSRegions: US_EAST_1 (primary), US_EAST_2, EU_WEST_1Instance Size: M10Cluster Type: Replica SetElectable Nodes: 2 / 2 / 1Backup: SnapshotCompute Autoscaling: Enabled (M10–M30)Disk Autoscaling: EnabledThe cluster is now being provisioned — it will take afew minutes to reach IDLE state. You can use``atlas-inspect-cluster`` to poll its status.
Encryption at Rest with a Customer-Managed Key
To encrypt a cluster with a customer-managed key, name the key provider in your prompt. The provider must already have a valid Encryption at Rest configuration in the project. The tool selects an existing configuration, it can't create or modify one. To learn how to configure a key provider, see Encryption at Rest using Customer Key Management.
If you don't name a provider, the tool uses the customer-managed key configured for the cluster's cloud provider when a valid configuration exists. Otherwise, the cluster uses the default Atlas Encryption at Rest.
Create a dedicated Atlas cluster named myEncryptedClusterin project myProject on AWS in US East, encrypted with ourAWS customer-managed key
I'll create a dedicated Atlas cluster on AWS inUS_EAST_1 using your AWS KMS customer-managed key.Ran ``atlas-create-cluster``Cluster creation is underway. Here's a summary:**Cluster Details:**Name: myEncryptedClusterProject ID: XXXProvider: AWSRegions: US_EAST_1Instance Size: M10Cluster Type: Replica SetEncryption at Rest Provider: AWSBackup: SnapshotCompute Autoscaling: Enabled (M10–M30)Disk Autoscaling: EnabledThe cluster is now being provisioned — it will take afew minutes to reach IDLE state. You can use``atlas-inspect-cluster`` to poll its status.
Upgrade an Atlas Cluster
The atlas-upgrade-cluster tool supports the following upgrade paths:
Free to Flex
Free to M10
Flex to M10
The tool also scales a dedicated cluster to a different M10–M80 instance size and updates its compute autoscaling settings.
Connected to a Cluster
If you configured a connection string in your MCP settings, or you connected using the atlas-connect-cluster tool, the MCP Server infers the cluster name, project, and current tier from your connection.
Upgrade my current Atlas cluster to Flex
I'll upgrade myFreeCluster to Flex tier.First, let me confirm the cluster details:Ran ``atlas-inspect-cluster``The cluster is a free cluster eligiblefor upgrade.Now I'll perform the upgrade:Ran ``atlas-upgrade-cluster``The upgrade request was submitted successfully.**Cluster Upgrade Details:**Cluster Name: myFreeClusterPrevious Tier: FreeNew Tier: FlexRegion: US East (US_EAST_1)Provider: AWSThe upgrade may take a few minutes to complete.
Not Connected to a Cluster
If you do not have an active cluster connection, provide the cluster name and project in your prompt. You can optionally specify the target tier, provider, and region.
Upgrade my Atlas cluster named myFlexClusterin project myProject to M10 on AWS in US East
I'll upgrade myFlexCluster to M10 dedicatedtier on AWS in US East.First, let me confirm the cluster details:Ran ``atlas-inspect-cluster``The cluster myFlexCluster is a Flex clustereligible for upgrade to M10.Now I'll perform the upgrade with the specifiedprovider and region:Ran ``atlas-upgrade-cluster``The upgrade request was submitted successfully.**Cluster Upgrade Details:**Cluster Name: myFlexClusterPrevious Tier: FlexNew Tier: M10 (Dedicated)Cluster Type: Replica SetNode Count: 3Region: US East (US_EAST_1)Provider: AWSThe upgrade may take a few minutes to complete.
Scaling a Dedicated Cluster
To scale a dedicated cluster, specify at least one of the following options:
The new instance size
Whether to enable compute autoscaling
The minimum or maximum instance size for autoscaling
Scale my Atlas cluster named myDedicatedClusterin project myProject to M30 and let it autoscalebetween M20 and M50
I'll scale myDedicatedCluster to M30 with computeautoscaling between M20 and M50.First, let me confirm the cluster details:Ran ``atlas-inspect-cluster``The cluster myDedicatedCluster is an M10dedicated cluster.Now I'll scale the cluster:Ran ``atlas-upgrade-cluster``The scaling request was submitted successfully.**Cluster Scaling Details:**Cluster Name: myDedicatedClusterPrevious Tier: M10New Tier: M30Compute Autoscaling: Enabled (M20–M50)The change may take a few minutes to complete.You can use ``atlas-inspect-cluster`` to poll itsstatus.
Pause or Resume an Atlas Cluster
The atlas-pause-resume-cluster tool pauses or resumes a dedicated (M10+) Atlas cluster. Free and Flex clusters cannot be paused.
The tool requires the following parameters:
projectId
clusterName
action. Set action to PAUSE or RESUME.
Pause a Cluster
When you pause a cluster, it becomes unavailable for connections and does not incur compute costs. If the cluster is your current active connection, the MCP Server automatically disconnects from it after the cluster is paused.
Pause cluster test-cluster-1 from project XXX
I'll load the schema for the cluster pause tool first.Pausing cluster test-cluster-1 now.Ran ``atlas-pause-resume-cluster``test-cluster-1 has been paused. It will not incurcompute costs while paused.
Resume a Cluster
When you resume a cluster, it does not become immediately available for connections. Use atlas-inspect-cluster to poll the cluster state until it reaches IDLE.
Resume cluster test-cluster-1 from project XXX
Resuming cluster test-cluster-1 in project XXX.Ran ``atlas-pause-resume-cluster``The resume request for test-cluster-1 in project XXX hasbeen submitted successfully. The cluster won't beimmediately available — use the inspect cluster tool topoll its state until it shows IDLE.
Data Exploration
The following examples demonstrate how you can use the MongoDB MCP Server to explore and understand your MongoDB data.
List Available Databases
Discover what databases are available in your cluster and get insights about their contents.
Show my Atlas databases
Ran ``list-databases``Here are the databases in your Atlas cluster "TestCluster":**Sample Databases:**sample_mflix - 138.4 MB (Movie database with films, theaters, users, comments)sample_training - 53.6 MB (Training data for learning MongoDB)sample_airbnb - 55.3 MB (Airbnb listings and reviews data)sample_analytics - 10.0 MB (Analytics and customer data)sample_restaurants - 6.8 MB (Restaurant and review data)sample_weatherdata - 2.7 MB (Weather observation data)sample_geospatial - 1.3 MB (Geospatial data examples)sample_supplies - 1.1 MB (Supply chain data)sample_guides - 41 KB (Getting started guides)**System Databases:**local - 4.1 GB (MongoDB internal database)admin - 365 KB (Administrative database)Your cluster contains MongoDB's sample datasets, which aregreat for learning and testing. The largest databases aresample_mflix (movies), sample_training, and sample_airbnb.Would you like me to explore any specific database or showyou the collections within one of them?
Explore Collections
Dive deeper into a specific database to understand its structure and collections.
Show the collections in the Atlas sample_mflix database
Ran ``list-collections``Here are the collections in the sample_mflix database:**Core Collections:**movies - Main collection containing movie data(titles, genres, cast, ratings, etc.)users - User profiles and account informationcomments - User comments and reviews on moviestheaters - Movie theater locations and detailssessions - User session data**Additional Collections:**embedded_movies - Movies collection with embedded/denormalized data structureThe movies collection contains detailed informationabout films including plot, cast, directors, ratings,release dates, and genres. The comments collection links tomovies and users to store user reviews and discussions.Would you like me to explore any specific collection in moredetail, such as showing sample documents or collectionstatistics?
Data Analysis
Analyize your MongoDB data to identify patterns and trends.
Summarize the Atlas movies collection by thrillers
I'll help you analyze the Atlas movies collection focusingon thrillers. First, let me check what databases areavailable in your connected cluster.Ran ``list-databases``Perfect! I can see you have the sample_mflix database whichcontains the movies collection. Let me check the collectionsin that database:Ran ``list-collections``Great! Now let me analyze the movies collection to findthrillers and provide a summary. First, let me check theschema to understand how genres are stored:Ran ``collection-schema``Perfect! I can see that genres are stored as an array ofstrings. Now let me get a count of thriller movies and thenperform an aggregation to summarize them:Ran ``count``Now let me create a comprehensive summary of thriller moviesusing aggregation:Ran ``aggregate``I see there are some data quality issues. Let me get betterdata by filtering for movies with numeric ratings:Ran ``aggregate``Now let me get some more summary statistics by decade:Ran ``aggregate``Here's a comprehensive analysis of thriller movies in yourAtlas sample_mflix collection:**Overall Statistics**Total Thriller Movies: 2,454 filmsTime Span: 1924 to 2011Average Rating: 6.3/10 (IMDb)Average Runtime: 105 minutesTotal IMDb Votes: 85.8 million across all thrillers**Top-Rated Thriller Movies**Drishyam (2013) - 8.9/10 - Indian thriller directed by Jeethu JosephTinker Tailor Soldier Spy (1979) - 8.7/10 - British spy thrillerRear Window (1954) - 8.6/10 - Alfred Hitchcock classicThe Silence of the Lambs (1991) - 8.6/10 - Psychological thrillerSe7en (1995) - 8.6/10 - David Fincher crime thrillerThe Usual Suspects (1995) - 8.6/10 - Neo-noir mysteryLéon: The Professional (1994) - 8.6/10 - Action thrillerPsycho (1960) - 8.6/10 - Another Hitchcock masterpieceMemento (2000) - 8.5/10 - Christopher Nolan psychological thriller**Trends by Decade**1920s-1950s: Few thrillers but high quality (avg 7.2-7.8 rating)1960s-1970s: Growing popularity, still maintaining quality1980s: Significant growth (200 films), quality decline begins1990s: Peak production era (417 films), avg 6.3 rating2000s: Highest volume (854 films), avg 6.24 rating2010s: 730 films, lowest average rating (6.12)The data shows that while thriller production increaseddramatically from the 1980s onward, the average quality (asmeasured by IMDb ratings) has generally declined, suggestingthe genre became more commercialized with higher volume butpotentially lower artistic standards in recent decades.
Database Operations
The following examples demonstrate how to use the MongoDB MCP Server to perform common database operations.
Insert New Documents
Add new data to your collections.
Add a document to the movies_copy collection
I'll add a new document to the movies_copy collection. Letme create a sample movie document with the same structure asthe existing movies:Ran ``insert-many``Perfect! I've successfully added a new movie document to themovies_copy collection. Here's what I added:**New Movie Added:**Title: "The AI Thriller"Genres: Thriller, Sci-Fi, DramaYear: 2024Runtime: 118 minutesIMDb Rating: 7.8/10 (125,000 votes)Cast: John Smith, Sarah Johnson, Michael ChenDirector: Alex RodriguezRating: PG-13The document was inserted with ID: 684b15fb5084ddef1f265e8fLet me verify the collection now has one additionaldocument:Ran ``count``Confirmed! The movies_copy collection now contains 21,350documents (up from 21,349), including your new thrillermovie about AI consciousness.
Create New Collections
Create and customize new collections.
Create a new collection to store movie purchases data thatincludes geospatial and timeseries fields
I'll create a new collection for storing movie purchasesdata with geospatial and timeseries fields. Let me firstcreate the collection and then add some sample documentswith the appropriate structure.Ran ``create-collection``Now I'll insert sample documents that include geospatialdata (customer location, theater location) and timeseriesdata (purchase timestamp, viewing timestamp):Ran ``insert-many``Perfect! I've created the movie_purchases collection withsample data that includes both geospatial and timeseriesfields. Here's what the collection contains:**Collection Structure****Geospatial Fields:**customer_location: GeoJSON Point with customer's coordinatestheater_location: GeoJSON Point with theater coordinatescustomer_address: Human-readable address information**Timeseries Fields:**purchase_timestamp: When the purchase was madeviewing_timestamp: When the movie was actually watchedviewing_duration_minutes: How long the customer watchedcompletion_percentage: Percentage of movie completed**Sample Data Added:**Purchase 1: Customer in San Francisco bought "The Shawshank Redemption" rental for $12.99Purchase 2: Customer in New York purchased "Pulp Fiction" for $15.99Purchase 3: Customer in Los Angeles rented "Se7en" for $9.99Now let me create a geospatial index to optimizelocation-based queries:Ran ``create-index``Excellent! The movie_purchases collection is now ready with:- Geospatial capabilities - 2dsphere index for location-based queries- Timeseries optimization - Index on purchase timestamps- Sample data - 3 purchase records across different US citiesThis collection can now support queries like:- Finding purchases within a certain radius of a location- Analyzing purchase patterns over time- Correlating viewing behavior with geographic regions- Time-based analytics and trending
Copy an Existing Collection
Create a backup or duplicate of an existing collection.
Make a copy of the movies collection named movies_copy
I'll create a copy of the movies collection namedmovies_copy. I'll use an aggregation pipeline with $out tocopy all documents from the movies collection to a newmovies_copy collection.Ran ``aggregate``Perfect! I've successfully created a copy of the moviescollection named movies_copy. Let me verify the copy wascreated correctly by checking the document count:Ran ``count``Found 21349 documents in the collection "movies_copy"Excellent! The movies_copy collection has been successfullycreated with all 21,349 documents from the original moviescollection. The copy operation completed successfully andyou now have an identical backup of your movies collection.
Data Export and Sharing
The following example demonstrates how to export query results for sharing or further processing in external tools.
Generate comprehensive reports and export them for use in other applications or for sharing with team members.
The exported results are saved to a file on the computer that runs the MCP Server. You can also access the exported data through the exported-data resource using the AI client application.
The export file is stored in the file system path specified by the exportPath configuration option. The export file is eligible for deletion after the time period specified by the exportTimeout configuration option. For additional details, see Export Data from MongoDB MCP Server.
Summarize and export the contents of the movies collection.
I'll help you summarize and export the contents of the moviescollection from your connected MongoDB Atlas cluster. Let's dothis in two steps:1. First, I'll create a summary of the movies collection using an aggregation pipeline.2. Then I'll export the results using the export tool.Let's start by getting a summary of the movies collection:Ran ``aggregate``Now that we have a summary of the movies collection, let's createa more focused dataset to export. Let's get the top 10highest-rated movies:Ran ``aggregate``Now, let's export this data using the MCP Server export tool:Ran ``export``I've successfully summarized and exported the contents of themovies collection from your MongoDB Atlas cluster. Here's abreakdown of what I did:**Movies Collection Summary****Collection Overview:**The collection contains 21,349 movie documentsTime span: 1896 to 2016 (120 years of cinema history)Average IMDb rating: 6.66 out of 10Average runtime: ~104 minutes**Top Genres:**Drama (12,385 movies)Comedy (6,532 movies)Romance (3,318 movies)Crime (2,457 movies)Thriller (2,454 movies)**Top Directors:**Woody Allen (40 movies)Martin Scorsese (32 movies)Takashi Miike (31 movies)Steven Spielberg (29 movies)John Ford (29 movies)**Top Languages:**English (14,639 movies)French (2,405 movies)Spanish (1,600 movies)German (1,377 movies)Italian (1,228 movies)**Highest Rated Movies:**Band of Brothers (2001) - 9.6/10Planet Earth (2006) - 9.5/10The Civil War (1990) - 9.4/10A Brave Heart: The Lizzie Velasquez Story (2015) - 9.4/10Cosmos (1980) - 9.3/10**Export Details**The data has been exported to a JSON file inrelaxed format. You can access the exported file at:/Users/XXX/.mongodb/mongodb-mcp/exports/68b8c10a6d0291128800be0b/sample_mflix.movies.68b8c2496d0291128800be0d.jsonThe export includes:- Genre summary with counts and average ratings- Runtime statistics (min, max, average)- Year-by-decade summary with counts and ratings- Top directors with film counts- Language distribution- Top 10 highest-rated moviesThis export provides a comprehensive overview of the moviescollection that can be easily shared or imported into other toolsfor further analysis or visualization.
Local Atlas Deployments
You can use the Local MCP with local Atlas deployments. To do so, you must install Docker. For an introduction to local Atlas deployments, see Create a Local Atlas Deployment.
The following examples show how to use the MongoDB MCP Server to interact with and create local Atlas deployments.
List Local Atlas Deployments
The following example lists local Atlas deployments.
List all local Atlas deployments.
I'll list all the local Atlas deployments for you.Ran ``atlas-local-list-deployments``Here are all your local Atlas deployments:[ { "name": "local7356", "state": "RUNNING", "mongoDbVersion": "8.2.1" }]You currently have one Atlas Local deployment named local7356that is running MongoDB version 8.2.1.
Connect to Local Atlas Deployment and List Databases
The following example connects to a local Atlas deployment named local7356 and lists the databases.
Connect to my local Atlas deployment local7356 and list thedatabases.
I'll connect to your local Atlas deployment local7356 and thenlist the databases.Ran ``atlas-local-connect-deployment``Now I'll list the databases in this deployment:Ran ``list-databases``Successfully connected to Atlas Local deployment local7356! Hereare the databases in this deployment:Found 4 databases:admin - 262,144 bytes (256 KB)config - 237,568 bytes (~232 KB)local - 1,163,264 bytes (~1.1 MB)testdb - 438,272 bytes (~428 KB)Your local Atlas deployment contains:System databases: admin, config, and local (standard MongoDBsystem databases)User database: testdb (your custom database)The local database has grown to about 1.1 MB, which is normal forlocal operations and metadata storage. Would you like me toexplore any of these databases further, such as showing thecollections in testdb?
Create New Local Atlas Deployment with Database and Collection
The following example creates a new local Atlas deployment with a database and an example collection. To run the example, you must disable read only mode.
Create a new local Atlas deployment, connect to it, create acollection with sample pizza orders data, and then retrieve thesample data.
I'll help you create a new local Atlas deployment, connect to it,create a collection with sample pizza orders data, and thenretrieve it. Let me break this down into steps:Created 4 todosNow let me start with the first task:Starting (1/4) Create new local Atlas deploymentRan ``atlas-local-create-deployment``Great! Created deployment local5528. Now let me mark that ascompleted and connect to it:Starting (2/4) Connect to new deploymentRan ``atlas-local-connect-deployment``Perfect! Now let me create the pizza orders collection with sampledata:Starting (3/4) Create pizza orders collectionRan ``create-collection``Now let me insert sample pizza orders data:Great! Now let me retrieve and display the sample data:Starting (4/4) Retrieve and display sample dataRan ``find``Completed (4/4) Retrieve and display sample dataPerfect! I've successfully completed all the tasks. Here's asummary of what was accomplished:Task Completed Successfully1. Created New Local Atlas DeploymentDeployment Name: local5528Container ID: XXXStatus: Running2. Connected to the New DeploymentSuccessfully connected to deployment local55283. Created Pizza Orders CollectionDatabase: pizzarestaurantCollection: ordersDocuments Inserted: 5 pizza orders4. Sample Pizza Orders Data CreatedThe collection now contains 5 realistic pizza orders with thefollowing details:Order ORD-001 - John Smith (New York)Margherita Pizza (Large) + Pepperoni Pizza (Medium)Total: $34.98 | Status: Completed | DeliveryOrder ORD-002 - Sarah Johnson (Brooklyn)2x Hawaiian Pizza (Large) + Caesar SaladTotal: $50.97 | Status: Preparing | PickupOrder ORD-003 - Mike Chen (Manhattan)Meat Lovers Pizza (Extra Large) + 2x Garlic Bread + 3x SodaTotal: $40.95 | Status: Delivered | DeliveryOrder ORD-004 - Emily Davis (Queens)Veggie Supreme Pizza (Medium)Total: $17.99 | Status: Ready | PickupOrder ORD-005 - David Wilson (Staten Island)BBQ Chicken Pizza (Large) + Buffalo WingsTotal: $35.98 | Status: Out for Delivery | DeliveryData Structure Features:Customer Information: Name, phone, email, complete addressOrder Details: Order ID, date, delivery type, payment method, statusItems: Pizza types, sizes, quantities, prices, detailed toppingsFinancial Data: Individual item prices and total amountsYour new local Atlas deployment is now ready with a fullyfunctional pizza restaurant orders system!
Delete Local Atlas Deployment
The following example deletes a local Atlas deployment named local5528. To run the example, you must disable read only mode.
Delete my local Atlas deployment local5528.
I'll delete your local Atlas deployment local5528 for you.Ran ``atlas-local-delete-deployment``
After the atlas-local-delete-deployment tool deletes the local Atlas deployment, the AI client might respond that the deployment has already been deleted. This is because the atlas-local-delete-deployment tool ran successfully and the local Atlas deployment no longer exists.
Performance Optimization
The following examples demonstrate how you can use the MongoDB MCP Server to identify and resolve performance issues. The actual output for your prompts will depend on whether your cluster is experiencing performance issues, so your output might not match the examples exactly.
Identify and analyze slow-performing queries to understand performance bottlenecks.
Note
When performing slow query analysis, the MongoDB MCP Server retrieves a sample of slow queries, capped at 50 queries. The sample includes up to 50 most recent slow queries that match any specified conditions in your prompt to ensure optimal performance and response times.
Query for all slow queries in the cluster:
Show me slow queries in my cluster
Ran ``atlas-get-performance-advisor``I found extensive slow query logs for ClusterM10. Here's a summary of the slow queries detected:**Query Types and Patterns****Most Common Slow Queries:****Collection Statistics Queries ($collStats)**- **Collections**: SchemaAdvisor.Call to Action: Remove unnecessary indexes and SchemaAdvisor.Call to Action: Remove unnecessary indexes 2- **Duration**: 30-100+ milliseconds- **Pattern**: These are MongoDB Automation Agent queries collecting storage statistics- **Frequency**: Very frequent (every 10 minutes)**Collection Statistics for mcp_db.new**- **Duration**: 30-60+ milliseconds- **Pattern**: Similar $collStats operations**Find Query on sample_db.test**- **Query**: {"find": "dbC", "filter": {"z": 10}}- **Duration**: 5 milliseconds- **Plan**: COLLSCAN (Collection Scan)- **Performance Issue**: Examined 10,001 documents but only returned 1- This matches the index suggestion we saw earlier!**Key Performance Issues****Inefficient Query on sample_db.test:**- The find query {"z": 10} is doing a full collection scan- This directly relates to the index suggestion we found: creating an index on field z would significantly improve this query- Currently examining 10,001 documents to find 1 result**Automation Agent Overhead:**- Many slow queries are from MongoDB Automation Agent collecting statistics- These are system-level operations that run regularly- Duration typically 30-100ms, which is acceptable for system operations**Recommendations****Implement the Suggested Index:**- Create an index on {"z": 1} for the sample_db.test collection- This will eliminate the collection scan and dramatically improve the find query performance**Monitor Automation Agent Performance:**- The frequent $collStats operations are normal but worth monitoring- Consider if the collection statistics collection frequency can be optimizedThe most actionable finding is the inefficient query on sample_db.test that would benefit from the index suggestion we identified earlier.
Query for general performance issues:
How is my cluster performance?
Ran ``atlas-get-performance-advisor``Based on the performance advisor data I retrieved for ClusterM10, here's an assessment of your cluster performance:**Overall Performance Assessment: Good with Room for Optimization****✅ Positive Indicators**- **Query Response Times**: Most queries are completing in reasonable timeframes (30-100ms)- **No Critical Issues**: No extremely slow queries (>1000ms) detected- **Stable Operations**: Consistent performance patterns over time- **System Health**: MongoDB Automation Agent operations are functioning normally**⚠️ Areas for Improvement****Inefficient Query Pattern:**- **Issue**: Find query {"z": 10} on sample_db.test collection- **Current**: Full collection scan examining 10,001 documents- **Impact**: Unnecessary resource consumption- **Solution**: Implement suggested index on field z**Resource Utilization:**- **CPU Usage**: Queries consuming 5-45+ CPU nanoseconds- **Memory**: Response sizes up to 602KB for statistics queries- **I/O**: Some queries showing storage read operations**📊 Performance Metrics Summary**- **Slow Query Count**: 50+ entries in recent logs- **Average Query Duration**: 30-100ms (acceptable range)- **Most Common Operations**: Collection statistics gathering- **Index Optimization Opportunity**: 1 significant improvement identified**🎯 Immediate Recommendations****High Priority**: Create index {"z": 1} on sample_db.test collection- **Expected Impact**: Eliminate collection scan, reduce query time from 5ms to <1ms- **Resource Savings**: Reduce CPU and I/O usage significantly**Medium Priority**: Monitor automation agent performance- Current 30-100ms for $collStats operations is acceptable- Consider optimizing if frequency becomes problematic**📈 Performance Grade: B+**Your cluster is performing well overall, but implementing the suggested index would elevate it to an A-grade performance level. The main bottleneck is the inefficient query pattern that can be easily resolved with proper indexing.Would you like me to help you implement the suggested index or dive deeper into any specific performance metrics?
Query for a specific operation type, duration, or namespace:
Show me slow writes for the past 24 hours in the movies collection
Ran ``atlas-get-performance-advisor``Based on the slow query logs from the sample_db.test collection, I can see that there are no slow write operations in this collection over the past 24 hours.**Analysis Summary****Slow Query Logs Found in sample_db.test:**- **1 slow query detected** - this is a READ operation (find query)- **No write operations found** in the slow query logs- Query occurred on 2025-09-30 at 14:52:56 UTC**Detailed Breakdown of the Slow Query****Query Details:**.. code-block:: javascript db.dbC.find({ "z": 10 })**Performance Characteristics:**- **Operation Type**: find (READ operation)- **Collection Scan**: ``"planSummary": "COLLSCAN"``- **Documents Examined**: 10,001 documents- **Keys Examined**: 0 (no index usage)- **Duration**: 6 milliseconds- **Results Returned**: 1 document- **Planning Time**: 1.78ms- **Mirrored Query**: Yes (read preference: secondaryPreferred)**Performance Issues:**- **Missing Index**: The query on field ``z`` is performing a collection scan- **Inefficient**: Examining 10,001 documents to find 1 result- **Read Preference**: Using secondaryPreferred (mirrored query)**Key Findings**✅ **Write Performance**: No slow write operations detected⚠️ **Read Performance**: One slow read operation due to missing index
Query for a specific execution time:
Show me queries longer than 5 seconds
Ran ``atlas-get-performance-advisor``Based on the slow query logs from your MongoDB Atlas cluster, I can see that there are no queries longer than 5 seconds in your cluster performance data.**Analysis Summary****Query Duration Analysis:**- All slow queries are under 5 seconds - the longest queries are around 117ms (0.117 seconds)- Most queries are between 30-100ms duration- No queries exceed 5 seconds (5000ms)**Detailed Breakdown of Slow Queries**The slow query logs show primarily MongoDB Automation Agent queries with the following characteristics:**Query Types Found:****SchemaAdvisor Collections** - MongoDB's automated performance monitoring queries- **Duration**: 30-117ms- **Operations**: ``$collStats`` aggregation queries- **Purpose**: Automated performance analysis**smol.woofer Collection** - User application queries- **Duration**: 33ms- **Operations**: Aggregation with ``$match`` and ``$lookup``- **Issue**: Collection scan (no index usage)**mcp_db.new Collection** - Storage statistics queries- **Duration**: 33-69ms- **Operations**: ``$collStats`` aggregation**sample_db.test Collection** - Find queries- **Duration**: 6ms- **Operations**: find with collection scan**Performance Status**: ✅ GoodYour cluster is performing well with:- No queries longer than 5 seconds- All slow queries are under 200ms- Most queries are under 100msThe slow queries are primarily from MongoDB's automated monitoring systems, which is normal and expected behavior.
Get Index Recommendations
Use the Performance Advisor to suggest indexes to create or drop to improve performance.
What indexes should I create or drop to improve performance?
Ran ``atlas-get-performance-advisor``Based on the performance advisor analysis of your MongoDB Atlas cluster "ClusterM10", here are the specific index recommendations:**Index to CREATE:****High Priority - Create Index on sample_db.test collection:**- **Index**: { "z": 1 }- **Weight**: 1,020,000 bytes (≈ 1.02 MB saved per query)- **Impact**: This index will significantly improve performance for queries filtering on the z field- **Reason**: The slow query logs show a query {"z": 10} that performed a collection scan (COLLSCAN) and examined 10,001 documents to return just 1 result**Indexes to DROP:****No Drop Recommendations Found**The performance advisor found no indexes that should be dropped at this time.**Additional Performance Insights:****Schema Recommendations:**- **Remove Unnecessary Indexes**: You have collections with more than 30 indexes, which can impact write performance- **Reduce Document Size**: Some documents exceed 2MB, which can cause performance issues- **Avoid Unbounded Arrays**: Some collections have arrays with over 10,000 entries**Slow Query Analysis:**The slow query logs show that most slow queries are from MongoDB's internal automation agent running $collStats operations, which is normal. However, there's one user query that would benefit significantly from the suggested index:- **Query**: db.dbC.find({"z": 10})- **Current Performance**: Collection scan examining 10,001 documents- **Expected Improvement**: With the suggested index, this should become an index scan examining only the matching documents**Recommended Action:**Create the index { "z": 1 } on the sample_db.test collection. This single index creation could save approximately 1MB of disk reads per query execution for queries filtering on the z field.
Optimize Your Schema
Get recommendations for improving your database schema design and structure.
Suggest schema improvements for my database
Ran ``atlas-get-performance-advisor``Based on the performance advisor analysis of your MongoDB Atlas cluster, here are the specific schema improvements recommended:**Critical Schema Issues Found:****1. Remove Unnecessary Indexes****Collections Affected:**- SchemaAdvisor.Call to Action: Remove unnecessary indexes- SchemaAdvisor.Call to Action: Remove unnecessary indexes 2**Issue**: Both collections have more than 30 indexes each**Impact:**- Slower write operations- Increased storage overhead- Longer index maintenance time- Reduced memory efficiency**Recommendation:**- Audit all indexes in these collections- Remove indexes that are not actively used by your queries- Keep only indexes that support your application's query patterns- Consider compound indexes instead of multiple single-field indexes**2. Reduce Document Size****Collections Affected:**- SchemaAdvisor.Call to Action: Reduce the size of documents- SchemaAdvisor.Call to Action: Reduce the size of documents 2**Issue**: Documents larger than 2MB found**Impact:**- Documents cannot be stored in MongoDB (16MB limit)- Performance degradation for large documents- Increased memory usage- Slower network transfer**Recommendations:**- Split large documents into smaller, related documents- Use GridFS for storing large binary data- Normalize data by moving large arrays or objects to separate collections- Archive old data to reduce document size- Compress data where appropriate**3. Avoid Unbounded Arrays****Collections Affected:**- SchemaAdvisor.Call to Action: Avoid using unbounded arrays in documents**Issue**: Arrays with over 10,000 entries detected**Impact:**- Poor query performance on array elements- Memory consumption issues- Index inefficiency- Difficult to maintain and update**Recommendations:**- Move large arrays to separate collections with references- Implement pagination for array access- Use embedded documents with limits (e.g., max 100 items)- Consider denormalization for frequently accessed array elements
Vector Search
The following examples demonstrate how to use the MongoDB MCP Server to work with MongoDB Vector Search. To learn more about how the MCP Server works with vector search, see Vector Search Support.
Note
To use automatic embedding generation, you must configure the MCP Server with a Voyage AI API key.
Create and Manage Vector Search Indexes
Create, drop, and list vector search indexes for your collections.
Create a vector search index on the sample_db.products collectionfor the embeddings field with 1024 dimensionsusing dot product similarity
I'll help you create a vector search index on the MongoDB collection. Let me first check the available MongoDB tools and then create the index.Now I'll create the vector search index: Ran ``create-index``Vector search index created successfully!The index embeddings_vector_index has been created on the sample_db.products collection for the embeddings field with:1024 dimensionsDot product similarityNote that vector search indexes can take some time to build. You can check the index status using the collection-indexes tool.
Show me all vector search indexes on the sample_db.products collection
Ran ``collection-indexes``The sample_db.products collection has 1 vector search index:embeddings_vector_indexType: vectorSearchStatus: READY ✓Queryable: YesField: embeddingsDimensions: 2048Similarity: dotProductQuantization: noneThe index is ready and can be used for vector search queries.
Drop the vector search index from the sample_db.products collection
First, let me check what indexes exist on this collection to identify the vector search index.I can see there's a vector search index named embeddings_vector_index on the collection.Now I need to activate the index management tools to drop it. Ran ``drop-index``Done! The vector search index embeddings_vector_index has been successfully dropped from the sample_db.products collection.
Insert Documents with Automatic Embeddings
When you configure a Voyage AI API key, the MCP Server automatically generates embeddings when inserting documents. You can provide raw text values, and the server generates the embeddings for fields with vector search indexes.
Insert documents into the sample_db database and products collection.Use the voyage-3-large embedding model to generatevector embeddings from descriptions for the `embeddings` field.1. name: "Headphones", description: "Premium wireless noise-canceling headphones with 30-hour battery"2. name: "Earbuds", description: "True wireless earbuds with active noise cancellation"3. name: "Monitor", description: "24-inch 4K monitor with 1ms response time"4. name: "Keyboard", description: "Mechanical keyboard with customizable RGB lighting"5. name: "Mouse", description: "Wireless ergonomic mouse with programmable buttons"
I'll insert these documents with embeddings for their descriptions.Let me activate the necessary tools and generate embeddings. Ran ``insert-many``Successfully inserted 5 documents into sample_db.products:Headphones - Premium wireless noise-canceling headphones with 30-hour batteryEarbuds - True wireless earbuds with active noise cancellationMonitor - 24-inch 4K monitor with 1ms response timeKeyboard - Mechanical keyboard with customizable RGB lightingMouse - Wireless ergonomic mouse with programmable buttonsThe documents have been inserted with their descriptions embedded in the embeddings field.When you perform vector searches using the $vectorSearch aggregation stage, the MCP serverwill automatically generate the proper vector embeddings from the text for comparison.
Run a Vector Search Query
When you configure a Voyage AI API key, the MCP Server automatically generates embeddings when running vector search queries. You can provide the raw text and the server automatically generates embeddings for the query.
Run a vector search query on sample_db.products on the 'embeddings' fieldusing the vector search index to find products that I can use to listen to music.
I'll search for products related to listening to music using vector search.Ran ``aggregate``Products for Listening to Music1. Earbuds (Score: 0.77) True wireless earbuds with active noise cancellation2. Headphones (Score: 0.77) Premium wireless noise-canceling headphones with 30-hour batteryThese are the two most relevant products for listening to music in your database.Both scored highly on the semantic search and are specifically designed for audio listening,with the earbuds and headphones being the clear top matches.
Lexical Search
The following examples demonstrate how to use the MongoDB MCP Server to work with MongoDB Search. To learn more about how the MCP Server works with lexical search, see Lexical Search Support.
Create and Manage Lexical Search Indexes
Create, drop, and list lexical search indexes for your collections.
Create a lexical search index on the sample_db.products collectionfor the description field
I'll help you create a lexical search index on the MongoDB collection. Let me first check the available MongoDB tools and then create the index.Now I'll create the lexical search index: Ran ``create-index``Lexical search index created successfully!The index description_search_index has been created on the sample_db.products collection for the description field.Note that lexical search indexes can take some time to build. You can check the index status using the collection-indexes tool.
Show me all lexical search indexes on the sample_db.products collection
Ran ``collection-indexes``The sample_db.products collection has 1 lexical search index:description_search_indexType: searchStatus: READY ✓Queryable: YesMapped field: descriptionThe index is ready and can be used for lexical search queries.
Drop the lexical search index from the sample_db.products collection
First, let me check what indexes exist on this collection to identify the lexical search index.I can see there's a lexical search index named description_search_index on the collection.Now I need to activate the index management tools to drop it. Ran ``drop-index``Done! The lexical search index description_search_index has been successfully dropped from the sample_db.products collection.
Run a Lexical Search Query
Run lexical search queries with the aggregate tool using the $search aggregation stage.
Run a lexical search query on sample_db.products on the 'description' fieldusing the lexical search index to find products that mention wireless.
I'll search for products that mention wireless using lexical search.Ran ``aggregate``Products Matching "wireless"1. Headphones (Score: 1.42) Premium wireless noise-canceling headphones with 30-hour battery2. Mouse (Score: 1.15) Wireless ergonomic mouse with programmable buttonsThese are the top matches for products whose description mentions "wireless."
Get Lexical Search Result Metadata
Use the aggregate tool with the $searchMeta aggregation stage to return metadata about a lexical search, such as a count of matching documents, instead of the matching documents themselves.
How many products have "wireless" in the description onsample_db.products using the lexical search index
I'll get the count of products that mention wireless using lexical search metadata.Ran ``aggregate``5 products in sample_db.products have "wireless" in the description.
Next Steps
For more information about configuring and using the MongoDB MCP Server: