Provides full featured access to MongoDB databases using natural language via LLMs to perform queries, run aggregations, optimize performance, and more. The server connects to MongoDB instances to allow exploration, querying, and management of databases, collections, and documents.
MongoDB Lens
MongoDB Lens is a local Model Context Protocol (MCP) server with full featured access to MongoDB databases using natural language via LLMs to perform queries, run aggregations, optimize performance, and more.
Contents
Quick Start
- Install MongoDB Lens 
- Configure MongoDB Lens 
- Set up your MCP Client (e.g. Claude Desktop, Cursor, etc) 
- Explore your MongoDB databases with natural language queries 
Features
Tools
- add-connection-alias: Add a new MongoDB connection alias
- aggregate-data: Execute aggregation pipelines
- analyze-query-patterns: Analyze live queries and suggest optimizations
- analyze-schema: Automatically infer collection schemas
- bulk-operations: Perform multiple operations efficiently (requires confirmation for destructive operations)
- clear-cache: Clear memory caches to ensure fresh data
- collation-query: Find documents with language-specific collation rules
- compare-schemas: Compare schemas between two collections
- connect-mongodb: Connect to a different MongoDB URI
- connect-original: Connect back to the original MongoDB URI used at startup
- count-documents: Count documents matching specified criteria
- create-collection: Create new collections with custom options
- create-database: Create a new database with option to switch to it
- create-index: Create new indexes for performance optimization
- create-timeseries: Create time series collections for temporal data
- create-user: Create new database users with specific roles
- current-database: Show the current database context
- delete-document: Delete documents matching specified criteria (requires confirmation)
- distinct-values: Extract unique values for any field
- drop-collection: Remove collections from the database (requires confirmation)
- drop-database: Drop a database (requires confirmation)
- drop-index: Remove indexes from collections (requires confirmation)
- drop-user: Remove database users (requires confirmation)
- explain-query: Analyze query execution plans
- export-data: Export query results in JSON or CSV format
- find-documents: Run queries with filters, projections, and sorting
- generate-schema-validator: Generate JSON Schema validators
- geo-query: Perform geospatial queries with various operators
- get-stats: Retrieve database or collection statistics
- gridfs-operation: Manage large files with GridFS buckets
- insert-document: Insert one or more documents into collections
- list-collections: Explore collections in the current database
- list-connections: View all available MongoDB connection aliases
- list-databases: View all accessible databases
- rename-collection: Rename existing collections (requires confirmation when dropping targets)
- shard-status: View sharding configuration for databases and collections
- text-search: Perform full-text search across text-indexed fields
- transaction: Execute multiple operations in a single ACID transaction
- update-document: Update documents matching specified criteria
- use-database: Switch to a specific database context
- validate-collection: Check for data inconsistencies
- watch-changes: Monitor real-time changes to collections
Resources
- collection-indexes: Index information for a collection
- collection-schema: Schema information for a collection
- collection-stats: Performance statistics for a collection
- collection-validation: Validation rules for a collection
- collections: List of collections in the current database
- database-triggers: Database change streams and event triggers configuration
- database-users: Database users and roles in the current database
- databases: List of all accessible databases
- performance-metrics: Real-time performance metrics and profiling data
- replica-status: Replica set status and configuration
- server-status: Server status information
- stored-functions: Stored JavaScript functions in the current database
Prompts
- aggregation-builder: Step-by-step creation of aggregation pipelines
- backup-strategy: Customized backup and recovery recommendations
- data-modeling: Expert advice on MongoDB schema design for specific use cases
- database-health-check: Comprehensive database health assessment and recommendations
- index-recommendation: Get personalized index suggestions based on query patterns
- migration-guide: Step-by-step MongoDB version migration plans
- mongo-shell: Generate MongoDB shell commands with explanations
- multi-tenant-design: Design MongoDB multi-tenant database architecture
- query-builder: Interactive guidance for constructing MongoDB queries
- query-optimizer: Optimization recommendations for slow queries
- schema-analysis: Detailed collection schema analysis with recommendations
- schema-versioning: Manage schema evolution in MongoDB applications
- security-audit: Database security analysis and improvement recommendations
- sql-to-mongodb: Convert SQL queries to MongoDB aggregation pipelines
Other Features
Other Features: Overview
MongoDB Lens includes numerous other features:
- Config File: Custom configuration via - ~/.mongodb-lens.[jsonc|json]
- Env Var Overrides: Override config settings via - process.env.CONFIG_*
- Confirmation System: Two-step verification for destructive operations 
- Multiple Connections: Define and switch between named URI aliases 
- Component Disabling: Selectively disable tools, prompts or resources 
- Connection Resilience: Auto-reconnection with exponential backoff 
- Query Safeguards: Configurable limits and performance protections 
- Error Handling: Comprehensive JSONRPC error codes and messages 
- Schema Inference: Efficient schema analysis with intelligent sampling 
- Credential Protection: Connection string password obfuscation in logs 
- Memory Management: Auto-monitoring and cleanup for large operations 
- Smart Caching: Optimized caching for schema, indexes, fields and collections 
- Backwards Compatible: Support both modern and legacy MongoDB versions 
Other Features: New Database Metadata
MongoDB Lens inserts a metadata collection into each database it creates.
This metadata collection stores a single document containing contextual information serving as a permanent record of the database's origin while ensuring the new and otherwise empty database persists in MongoDB's storage system.
Once you've added your own collections to your new database, you can safely remove the metadata collection via the drop-collection tool:
- "Drop the new database's metadata collection" ➥ Uses - drop-collectiontool (with confirmation)
Installation
MongoDB Lens can be installed and run in several ways:
- NPX (Easiest) 
Installation: NPX
The easiest way to run MongoDB Lens is using NPX.
First, ensure Node.js is installed:
Then, run MongoDB Lens via NPX:
If you encounter permissions errors with npx try running npx clear-npx-cache prior to running npx -y mongodb-lens (this clears the cache and re-downloads the package).
Installation: Docker Hub
Docker Hub requires Docker installed and running on your system.
First, ensure Docker is installed:
Then, run MongoDB Lens via Docker Hub:
Installation: Node.js from Source
- Clone the MongoDB Lens repository: git clone https://github.com/furey/mongodb-lens.git
- Navigate to the cloned repository directory: cd /path/to/mongodb-lens
- Ensure Node.js is installed: node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible
- Install Node.js dependencies: npm ci
- Start the server: # Using default connection string mongodb://localhost:27017 node mongodb-lens.js # Using custom connection string node mongodb-lens.js mongodb://your-connection-string
Installation: Docker from Source
Docker from source requires Docker installed and running on your system.
- Clone the MongoDB Lens repository: git clone https://github.com/furey/mongodb-lens.git
- Navigate to the cloned repository directory: cd /path/to/mongodb-lens
- Ensure Docker is installed: docker --version # Ideally >= v27.x
- Build the Docker image: docker build -t mongodb-lens .
- Run the container: # Using default connection string mongodb://localhost:27017 docker run --rm -i --network=host mongodb-lens # Using custom connection string docker run --rm -i --network=host mongodb-lens mongodb://your-connection-string
Installation Verification
To verify the installation, paste and run the following JSONRPC message into the server's stdio:
The server should respond with a list of databases in your MongoDB instance, for example:
MongoDB Lens is now installed and ready to accept MCP requests.
Installation: Older MongoDB Versions
If connecting to a MongoDB instance with a version < 4.0, the MongoDB Node.js driver used by the latest version of MongoDB Lens will not be compatible. Specifically, MongoDB Node.js driver versions 4.0.0 and above require MongoDB version 4.0 or higher.
To use MongoDB Lens with older MongoDB instances, you need to use a MongoDB Node.js driver version from the 3.x series (e.g. 3.7.4 which is compatible with MongoDB 3.6).
Older MongoDB Versions: Running from Source
- Clone the MongoDB Lens repository: git clone https://github.com/furey/mongodb-lens.git
- Navigate to the cloned repository directory: cd /path/to/mongodb-lens
- Modify - package.json:"dependencies": { ... - "mongodb": "^6.15.0", // Or whatever newer version is listed + "mongodb": "^3.7.4", // Or whatever 3.x version is compatible with your older MongoDB instance ... }
- Install Node.js dependencies: npm install
- Start MongoDB Lens: node mongodb-lens.js mongodb://older-mongodb-instance
This will use the older driver version compatible with your MongoDB instance.
You may also need to revert this commit to add back useNewUrlParser and useUnifiedTopology MongoDB configuration options.
Older MongoDB Versions: Using NPX or Docker
If you prefer to use NPX or Docker, you'll need to use an older version of MongoDB Lens that was published with a compatible driver.
For example, MongoDB Lens 8.3.0 uses MongoDB Node.js driver 3.7.4 (see: package-lock.json).
To run an older version of MongoDB Lens using NPX, specify the version tag:
Similarly for Docker:
Configuration
Configuration: MongoDB Connection String
The server accepts a MongoDB connection string as its only argument.
Example NPX usage:
MongoDB connection strings have the following format:
Example connection strings:
- Local connection: - mongodb://localhost:27017
- Connection to - mydatabasewith credentials from- admindatabase:- mongodb://username:password@hostname:27017/mydatabase?authSource=admin
- Connection to - mydatabasewith various other options:- mongodb://hostname:27017/mydatabase?retryWrites=true&w=majority
If no connection string is provided, the server will attempt to connect via local connection.
Configuration: Config File
MongoDB Lens supports extensive customization via JSON configuration file.
The config file is optional. MongoDB Lens will run with default settings if no config file is provided.
You only need to include the settings you want to customize in the config file. MongoDB Lens will use default settings for any omitted values.
MongoDB Lens supports both .json and .jsonc (JSON with comments) config file formats.
By default, MongoDB Lens looks for the config file at:
- ~/.mongodb-lens.jsoncfirst, then falls back to
- ~/.mongodb-lens.jsonif the former doesn't exist
To customize the config file path, set the environment variable CONFIG_PATH to the desired file path.
Example NPX usage:
Example Docker Hub usage:
Configuration: Config File Generation
You can generate a configuration file automatically using the config:create script:
This script extracts the example configuration file above and saves it to: ~/.mongodb-lens.jsonc
Config File Generation: Custom Path
You can specify a custom output location using the CONFIG_PATH environment variable.
- If - CONFIG_PATHhas no file extension, it's treated as a directory and- .mongodb-lens.jsoncis appended
- If - CONFIG_PATHends with- .json(not- .jsonc) comments are removed from the generated file
Example NPX usage:
Example Node.js usage:
Configuration: Multiple MongoDB Connections
MongoDB Lens supports multiple MongoDB URIs with aliases in your config file, allowing you to easily switch between different MongoDB instances using simple names.
To configure multiple connections, set the mongoUri config setting to an object with alias-URI pairs:
With this configuration:
- The first URI in the list (e.g. - main) becomes the default connection at startup
- You can switch connections using natural language: - "Connect to backup"or- "Connect to atlas"
- The original syntax still works: - "Connect to mongodb://localhost:27018"
- The - list-connectionstool shows all available connection aliases
When using the command-line argument to specify a connection, you can use either a full MongoDB URI or an alias defined in your configuration file.
To add connection aliases at runtime, use the add-connection-alias tool.
Configuration: Environment Variable Overrides
MongoDB Lens supports environment variable overrides for configuration settings.
Environment variables take precedence over config file settings.
Config environment variables follow the naming pattern:
Example overrides:
| Config Setting | Environment Variable Override | 
| 
 | 
 | 
| 
 | 
 | 
| 
 | 
 | 
| 
 | 
 | 
| 
 | 
 | 
| 
 | 
 | 
| 
 | 
 | 
For environment variable values:
- For boolean settings, use string values - 'true'or- 'false'.
- For numeric settings, use string representations. 
- For nested objects or arrays, use JSON strings. 
Example NPX usage:
Example Docker Hub usage:
Configuration: Cross-Platform Environment Variables
For consistent environment variable usage across Windows, macOS, and Linux, consider using cross-env:
- Install cross-env globally: # Using NPM npm install -g cross-env # Using Volta (see: https://volta.sh) volta install cross-env
- Prefix any NPX or Node.js environment variables in this document's examples: # Example NPX usage with cross-env cross-env CONFIG_DEFAULTS_QUERY_LIMIT='25' npx -y mongodb-lens@latest # Example Node.js usage with cross-env cross-env CONFIG_DEFAULTS_QUERY_LIMIT='25' node mongodb-lens.js
Client Setup
Client Setup: Claude Desktop
To use MongoDB Lens with Claude Desktop:
- Install Claude Desktop 
- Open - claude_desktop_config.json(create if it doesn't exist):- macOS: - ~/Library/Application Support/Claude/claude_desktop_config.json
- Windows: - %APPDATA%\Claude\claude_desktop_config.json
 
- Add the MongoDB Lens server configuration as per configuration options 
- Restart Claude Desktop 
- Start a conversation with Claude about your MongoDB data 
Claude Desktop Configuration Options
For each option:
- Replace - mongodb://your-connection-stringwith your MongoDB connection string or omit it to use the default- mongodb://localhost:27017.
- To use a custom config file, set - CONFIG_PATHenvironment variable.
- To include environment variables: - For NPX or Node.js add - "env": {}with key-value pairs, for example:"command": "/path/to/npx", "args": [ "-y", "mongodb-lens@latest", "mongodb://your-connection-string" ], "env": { "CONFIG_LOG_LEVEL": "verbose" }
- For Docker add - -eflags, for example:"command": "docker", "args": [ "run", "--rm", "-i", "--network=host", "--pull=always", "-e", "CONFIG_LOG_LEVEL=verbose", "furey/mongodb-lens", "mongodb://your-connection-string" ]
 
Option 1: NPX (Recommended)
Option 2: Docker Hub Image
Option 3: Local Node.js Installation
Option 4: Local Docker Image
Client Setup: MCP Inspector
MCP Inspector is a tool designed for testing and debugging MCP servers.
MCP Inspector starts a proxy server on port 3000 and web client on port 5173.
Example NPX usage:
- Run MCP Inspector: # Using default connection string mongodb://localhost:27017 npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest # Using custom connection string npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest mongodb://your-connection-string # Using custom ports SERVER_PORT=1234 CLIENT_PORT=5678 npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest
- Open MCP Inspector: http://localhost:5173 
MCP Inspector should support the full range of MongoDB Lens capabilities, including autocompletion for collection names and query fields.
For more, see: MCP Inspector
Client Setup: Other MCP Clients
MongoDB Lens should be usable with any MCP-compatible client.
For more, see: MCP Documentation: Example Clients
Data Protection
To protect your data while using MongoDB Lens, consider the following:
Data Protection: Read-Only User Accounts
When connecting MongoDB Lens to your database, the permissions granted to the user in the MongoDB connection string dictate what actions can be performed. When the use case fits, a read-only user can prevent unintended writes or deletes, ensuring MongoDB Lens can query data but not alter it.
To set this up, create a user with the read role scoped to the database(s) you're targeting. In MongoDB shell, you'd run something like:
Then, apply those credentials to your MongoDB connection string:
Using read-only credentials is a simple yet effective way to enforce security boundaries, especially when you're poking around schemas or running ad-hoc queries.
Data Protection: Working with Database Backups
When working with MongoDB Lens, consider connecting to a backup copy of your data hosted on a separate MongoDB instance.
Start by generating the backup with mongodump. Next, spin up a fresh MongoDB instance (e.g. on a different port like 27018) and restore the backup there using mongorestore. Once it's running, point MongoDB Lens to the backup instance's connection string (e.g. mongodb://localhost:27018/mydatabase).
This approach gives you a sandbox to test complex or destructive operations against without risking accidental corruption of your live data.
Data Protection: Data Flow Considerations
Data Flow Considerations: How Your Data Flows Through the System
When using an MCP Server with a remote LLM provider (such as Anthropic via Claude Desktop) understanding how your data flows through the system is key to protecting sensitive information from unintended exposure.
When you send a MongoDB related query through your MCP client, here’s what happens:
While this example uses a local MongoDB instance, the same principles apply to remote MongoDB instances.
- You submit a request➥ e.g. "Show me all users older than 30" 
- Your client sends the request to the remote LLM➥ The LLM provider receives your exact words along with a list of available MCP tools and their parameters. 
- The remote LLM interprets your request➥ It determines your intent and instructs the client to use a specific MCP tool with appropriate parameters. 
- The client asks MongoDB Lens to run the tool➥ This occurs locally on your machine via stdio. 
- MongoDB Lens queries your MongoDB database 
- MongoDB Lens retrieves your MongoDB query results 
- MongoDB Lens sends the data back to the client➥ The client receives results formatted by MongoDB Lens. 
- The client forwards the data to the remote LLM➥ The LLM provider sees the exact data returned by MongoDB Lens. 
- The remote LLM processes the data➥ It may summarize or format the results further. 
- The remote LLM sends the final response to the client➥ The client displays the answer to you. 
The remote LLM provider sees both your original request and the full response from MongoDB Lens. If your database includes sensitive fields (e.g. passwords, personal details, etc) this data could be unintentionally transmitted to the remote provider unless you take precautions.
Data Flow Considerations: Protecting Sensitive Data with Projection
To prevent sensitive data from being sent to the remote LLM provider, use the concept of projection when using tools like find-documents, aggregate-data, or export-data. Projection allows you to specify which fields to include or exclude in query results, ensuring sensitive information stays local.
Example projection usage:
- "Show me all users older than 30, but use projection to hide their passwords." ➥ Uses - find-documentstool with projection
Data Flow Considerations: Connection Aliases and Passwords
When adding new connection aliases using the add-connection-alias tool, avoid added aliases to URIs that contain passwords if you're using a remote LLM provider. Since your request is sent to the LLM, any passwords in the URI could be exposed. Instead, define aliases with passwords in the MongoDB Lens config file, where they remain local and are not transmitted to the LLM.
Data Flow Considerations: Local Setup for Maximum Safety
While outside the scope of this document, for the highest level of data privacy, consider using a local MCP client paired with a locally hosted LLM model. This approach keeps all requests and data within your local environment, eliminating the risk of sensitive information being sent to a remote provider.
Data Protection: Confirmation for Destructive Operations
MongoDB Lens implements a token-based confirmation system for potentially destructive operations, requiring a two-step process to execute tools that may otherwise result in unchecked data loss:
- First tool invocation: Returns a 4-digit confirmation token that expires after 5 minutes 
- Second tool invocation: Executes the operation if provided with the valid token 
For an example of the confirmation process, see: Working with Confirmation Protection
Tools that require confirmation include:
- drop-user: Remove a database user
- drop-index: Remove an index (potential performance impact)
- drop-database: Permanently delete a database
- drop-collection: Delete a collection and all its documents
- delete-document: Delete one or multiple documents
- bulk-operations: When including delete operations
- rename-collection: When the target collection exists and will be dropped
This protection mechanism aims to prevent accidental data loss from typos and unintended commands. It's a safety net ensuring you're aware of the consequences before proceeding with potentially harmful actions.
If you're working in a controlled environment where data loss is acceptable, you can configure MongoDB Lens to bypass confirmation and perform destructive operations immediately.
Bypassing Confirmation for Destructive Operations
You might want to bypass the token confirmation system.
Set the environment variable CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS to true to execute destructive operations immediately without confirmation:
Disabling confirmation tokens removes an important safety mechanism. It's strongly recommended to only use this option in controlled environments where data loss is acceptable, such as development or testing. Disable at your own risk.
Data Protection: Disabling Destructive Operations
Disabling Tools
MongoDB Lens includes several tools that can modify or delete data. To disable specific tools, add them to the disabled.tools array in your configuration file:
Resources and prompts can also be disabled via disabled.resources and disabled.prompts settings.
High-Risk Tools
These tools can cause immediate data loss and should be considered for disabling in sensitive environments:
- drop-user: Removes database users and their access permissions
- drop-index: Removes indexes (can impact query performance)
- drop-database: Permanently deletes entire databases
- drop-collection: Permanently deletes collections and all their documents
- delete-document: Removes documents matching specified criteria
- bulk-operations: Can perform batch deletions when configured to do so
- rename-collection: Can overwrite existing collections when using the drop target option
Medium-Risk Tools
These tools can modify data but typically don't cause immediate data loss:
- create-user: Creates users with permissions that could enable further changes
- transaction: Executes multiple operations in a transaction (potential for complex changes)
- update-document: Updates documents which could overwrite existing data
Read-Only Configuration
For a complete read-only configuration, disable all potentially destructive tools:
This configuration allows MongoDB Lens to query and analyze data while preventing any modifications, providing multiple layers of protection against accidental data loss.
Selective Component Enabling
In addition to disabling components, specify exactly which components should be enabled (implicitly disabling all others) using the enabled settings in your configuration file:
If a component appears in both enabled and disabled lists, the enabled setting takes precedence.
Tutorial
This following tutorial guides you through setting up a MongoDB container with sample data, then using MongoDB Lens to interact with it through natural language queries:
Tutorial: 1. Start Sample Data Container
This tutorial assumes you have Docker installed and running on your system.
If Docker is already running a container on port 27017, stop it before proceeding.
- Initialise the sample data container: docker run --name mongodb-sampledata -d -p 27017:27017 mongo:6
- Verify the container is running without issue: docker ps | grep mongodb-sampledata
Tutorial: 2. Import Sample Data
MongoDB provides several sample datasets which we'll use to explore MongoDB Lens.
- Download the sample datasets: curl -LO https://atlas-education.s3.amazonaws.com/sampledata.archive
- Copy the sample datasets into your sample data container: docker cp sampledata.archive mongodb-sampledata:/tmp/
- Import the sample datasets into MongoDB: docker exec -it mongodb-sampledata mongorestore --archive=/tmp/sampledata.archive
This will import several databases:
- sample_airbnb: Airbnb listings and reviews
- sample_analytics: Customer and account data
- sample_geospatial: Geographic data
- sample_mflix: Movie data
- sample_restaurants: Restaurant data
- sample_supplies: Supply chain data
- sample_training: Training data for various applications
- sample_weatherdata: Weather measurements
Tutorial: 3. Connect MongoDB Lens
Install MongoDB Lens as per the Quick Start instructions.
Set your MCP Client to connect to MongoDB Lens via: mongodb://localhost:27017
Omitting the connection string from your MCP Client configuration will default the connection string to mongodb://localhost:27017.
Example Claude Desktop configuration:
Tutorial: 4. Example Queries
With your MCP Client running and connected to MongoDB Lens, try the following example queries:
Example Queries: Basic Database Operations
- "List all databases" ➥ Uses - list-databasestool
- "What db am I currently using?" ➥ Uses - current-databasetool
- "Switch to the sample_mflix database" ➥ Uses - use-databasetool
- "Create a new db called test_db" ➥ Uses - create-databasetool
- "Create another db called analytics_db and switch to it" ➥ Uses - create-databasetool with switch=true
- "Drop test_db" ➥ Uses - drop-databasetool (with confirmation)
Example Queries: Collection Management
- "What collections are in the current database?" ➥ Uses - list-collectionstool
- "Create user_logs collection" ➥ Uses - create-collectiontool
- "Rename user_logs to system_logs" ➥ Uses - rename-collectiontool
- "Drop system_logs" ➥ Uses - drop-collectiontool (with confirmation)
- "Check the data consistency in the movies collection" ➥ Uses - validate-collectiontool
Example Queries: User Management
- "Create a read-only user for analytics" ➥ Uses - create-usertool
- "Drop the inactive_user account" ➥ Uses - drop-usertool (with confirmation)
Example Queries: Querying Data
- "Count all docs in the movies collection" ➥ Uses - count-documentstool
- "Find the top 5 movies with the highest IMDB rating" ➥ Uses - find-documentstool
- "Show me aggregate data for movies grouped by decade" ➥ Uses - aggregate-datatool
- "List all unique countries where movies were produced" ➥ Uses - distinct-valuestool
- "Search for movies containing godfather in their title" ➥ Uses - text-searchtool
- "Find German users with last name müller using proper collation" ➥ Uses - collation-querytool
Example Queries: Schema Analysis
- "What's the schema structure of the movies collection?" ➥ Uses - analyze-schematool
- "Compare users and comments schemas" ➥ Uses - compare-schemastool
- "Generate a schema validator for the movies collection" ➥ Uses - generate-schema-validatortool
- "Analyze common query patterns for the movies collection" ➥ Uses - analyze-query-patternstool
Example Queries: Data Modification
- "Insert new movie document: <your field data>" ➥ Uses - insert-documenttool
- "Update all movies from 1994 to add a 'classic' flag" ➥ Uses - update-documenttool
- "Delete all movies with zero ratings" ➥ Uses - delete-documenttool (with confirmation)
- "Run these bulk operations on the movies collection: <your JSON data>" ➥ Uses - bulk-operationstool
For specialized MongoDB operations (like array operations, bitwise operations, or other complex updates), use MongoDB's native operators via the update-document tool's update and options parameters.
Example Queries: Performance & Index Management
- "Create an index on the title field in the movies collection" ➥ Uses - create-indextool
- "Drop the ratings_idx index" ➥ Uses - drop-indextool (with confirmation)
- "Explain the execution plan for finding movies from 1995" ➥ Uses - explain-querytool
- "Get statistics for the current db" ➥ Uses - get-statstool with target=database
- "Show collection stats for the movies collection" ➥ Uses - get-statstool with target=collection
Example Queries: Geospatial & Special Operations
- "Switch to sample_geospatial db, then find all shipwrecks within 10km of coordinates [-80.12, 26.46]" ➥ Uses - geo-querytool
- "Switch to sample_analytics db, then execute a transaction to move funds between accounts: <account ids>" ➥ Uses - transactiontool
- "Create a time series collection for sensor readings" ➥ Uses - create-timeseriestool
- "Watch for changes in the users collection for 30 seconds" ➥ Uses - watch-changestool
- "List all files in the images GridFS bucket" ➥ Uses - gridfs-operationtool with operation=list
Example Queries: Export, Administrative & Other Features
- "Switch to sample_mflix db, then export the top 20 movies based on 'tomatoes.critic.rating' as a CSV with title, year and rating fields (output in a single code block)" ➥ Uses - export-datatool
- "Switch to sample_analytics db, then check its sharding status" ➥ Uses - shard-statustool
- "Clear the collections cache" ➥ Uses - clear-cachetool with target=collections
- "Clear all caches" ➥ Uses - clear-cachetool
- "Switch to sample_weatherdata db then generate an interactive report on its current state" ➥ Uses numerous tools 
Example Queries: Connection Management
- "Connect to mongodb://localhost:27018" ➥ Uses - connect-mongodbtool
- "Connect to mongodb+srv://username: ➥ Uses - connect-mongodbtool
- "Connect back to the original mongodb instance" ➥ Uses - connect-originaltool
- "Connect to replica set without validating the connection: <replica set details>" ➥ Uses - connect-mongodbtool with validateConnection=false
- "Add connection alias 'prod' for mongodb://username:password@prod-server:27017/mydb" ➥ Uses - add-connection-aliastool
Tutorial: 5. Working With Confirmation Protection
MongoDB Lens includes a safety mechanism for potentially destructive operations. Here's how it works in practice:
- Request to drop a collection: "Drop the collection named test_collection"
- MongoDB Lens responds with a warning and confirmation token: ⚠️ DESTRUCTIVE OPERATION WARNING ⚠️ You've requested to drop the collection 'test_collection'. This operation is irreversible and will permanently delete all data in this collection. To confirm, you must type the 4-digit confirmation code EXACTLY as shown below: Confirmation code: 9876 This code will expire in 5 minutes for security purposes.
- Confirm the operation by submitting the confirmation token: "9876"
- MongoDB Lens executes the operation: Collection 'test_collection' has been permanently deleted.
This two-step process prevents accidental data loss by requiring explicit confirmation.
If you're working in a controlled environment where data loss is acceptable, you can configure MongoDB Lens to bypass confirmation and perform destructive operations immediately.
Test Suite
MongoDB Lens includes a test suite to verify functionality across tools, resources, and prompts.
Test Suite: Running Tests
The test suite requires a CONFIG_MONGO_URI environment variable which can be set to:
- a MongoDB connection string (e.g. - mongodb://localhost:27017)
- mongodb-memory-server(for in-memory testing)
For convenience, the following scripts are available for running tests:
The test suite creates temporary databases and collections that are cleaned up after test completion.
Test Suite: Command Line Options
| Option | Description | 
| 
 | List all available tests without running them | 
| 
 | Run specific test(s) by name (comma-separated) | 
| 
 | Run all tests in specific group(s) (comma-separated) | 
| 
 | Run tests matching pattern(s) (comma-separated) | 
Test Suite: Examples
Disclaimer
MongoDB Lens:
- is licensed under the MIT License. 
- is not affiliated with or endorsed by MongoDB, Inc. 
- is written with the assistance of AI and may contain errors. 
- is intended for educational and experimental purposes only. 
- is provided as-is with no warranty—please use at your own risk. 
Support
If you've found MongoDB Lens helpful consider supporting my work through:
Buy Me a Coffee | GitHub Sponsorship
Contributions help me continue developing and improving this tool, allowing me to dedicate more time to add new features and ensuring it remains a valuable resource for the community.
This server cannot be installed
hybrid server
The server is able to function both locally and remotely, depending on the configuration or use case.
Full featured MCP Server for MongoDB database analysis.
- Contents
- Quick Start
- Features
- Installation
- Configuration
- Client Setup
- Data Protection
- Tutorial
- Test Suite
- Disclaimer
- Support
Related Resources
Related MCP Servers
- Asecurity-licenseAqualityAn MCP server that enables users to create and manage MongoDB Atlas clusters, users, and network access through natural language commands.Last updated -62011MIT License
- -security-license-qualityAn MCP server that enables large language models to interact directly with MongoDB databases, allowing them to query collections, inspect schemas, and manage data through natural language.Last updated -109MIT License
- -security-license-qualityOpen source MCP server specializing in easy, fast, and secure tools for Databases.Last updated -11,234Apache 2.0
- -security-license-qualityMongoDB MCP Server by CDataLast updated -MIT License