MongoDB Lens
hybrid server
The server is able to function both locally and remotely, depending on the configuration or use case.
Integrations
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
aggregate-data
: Execute aggregation pipelinesanalyze-query-patterns
: Analyze live queries and suggest optimizationsanalyze-schema
: Automatically infer collection schemasbulk-operations
: Perform multiple operations efficiently (requires confirmation for destructive operations)collation-query
: Find documents with language-specific collation rulescompare-schemas
: Compare schemas between two collectionsconnect-mongodb
: Connect to a different MongoDB URIconnect-original
: Connect back to the original MongoDB URI used at startupcount-documents
: Count documents matching specified criteriacreate-collection
: Create new collections with custom optionscreate-database
: Create a new database with option to switch to itcreate-index
: Create new indexes for performance optimizationcreate-timeseries
: Create time series collections for temporal datacreate-user
: Create new database users with specific rolescurrent-database
: Show the current database contextdelete-document
: Delete documents matching specified criteria (requires confirmation)distinct-values
: Extract unique values for any fielddrop-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 plansexport-data
: Export query results in JSON or CSV formatfind-documents
: Run queries with filters, projections, and sortinggenerate-schema-validator
: Generate JSON Schema validatorsgeo-query
: Perform geospatial queries with various operatorsget-stats
: Retrieve database or collection statisticsgridfs-operation
: Manage large files with GridFS bucketslist-collections
: Explore collections in the current databaselist-connections
: View all available MongoDB connection aliaseslist-databases
: View all accessible databasesmap-reduce
: Run MapReduce operations for complex data processingmodify-document
: Insert or update specific documentsrename-collection
: Rename existing collections (requires confirmation when dropping targets)shard-status
: View sharding configuration for databases and collectionstext-search
: Perform full-text search across text-indexed fieldstransaction
: Execute multiple operations in a single ACID transactionuse-database
: Switch to a specific database contextvalidate-collection
: Check for data inconsistencieswatch-changes
: Monitor real-time changes to collections
Resources
collection-indexes
: Index information for a collectioncollection-schema
: Schema information for a collectioncollection-stats
: Performance statistics for a collectioncollection-validation
: Validation rules for a collectioncollections
: List of collections in the current databasedatabase-triggers
: Database change streams and event triggers configurationdatabase-users
: Database users and roles in the current databasedatabases
: List of all accessible databasesperformance-metrics
: Real-time performance metrics and profiling datareplica-status
: Replica set status and configurationserver-status
: Server status informationstored-functions
: Stored JavaScript functions in the current database
Prompts
aggregation-builder
: Step-by-step creation of aggregation pipelinesbackup-strategy
: Customized backup and recovery recommendationsdata-modeling
: Expert advice on MongoDB schema design for specific use casesdatabase-health-check
: Comprehensive database health assessment and recommendationsindex-recommendation
: Get personalized index suggestions based on query patternsmigration-guide
: Step-by-step MongoDB version migration plansmongo-shell
: Generate MongoDB shell commands with explanationsmulti-tenant-design
: Design MongoDB multi-tenant database architecturequery-builder
: Interactive guidance for constructing MongoDB queriesquery-optimizer
: Optimization recommendations for slow queriesschema-analysis
: Detailed collection schema analysis with recommendationsschema-versioning
: Manage schema evolution in MongoDB applicationssecurity-audit
: Database security analysis and improvement recommendationssql-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-collection
tool (with confirmation)
Installation
MongoDB Lens can be installed and run in several ways:
Installation: NPX
The easiest way to run MongoDB Lens is using npx
.
First, ensure Node.js is installed:
Then, run MongoDB Lens via NPX:
Tip
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
Note
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
Note
Node.js from source requires Node.js installed and running on your system (suggestion: use Volta).
- Clone the MongoDB Lens repository:Copy
- Navigate to the cloned repository directory:Copy
- Ensure Node.js is installed:Copy
- Install Node.js dependencies:Copy
- Start the server:Copy
Installation: Docker from Source
Note
Docker from source requires Docker installed and running on your system.
- Clone the MongoDB Lens repository:Copy
- Navigate to the cloned repository directory:Copy
- Ensure Docker is installed:Copy
- Build the Docker image:Copy
- Run the container:Copy
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.
Configuration
- MongoDB Connection String
- Config File
- Config File Generation
- Multiple MongoDB Connections
- Environment Variable Overrides
- Cross-Platform Environment Variables
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
mydatabase
with credentials fromadmin
database:mongodb://username:password@hostname:27017/mydatabase?authSource=admin
- Connection to
mydatabase
with 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.
Note
The config file is optional. MongoDB Lens will run with default settings if no config file is provided.
Tip
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.
Tip
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.jsonc
first, then falls back to~/.mongodb-lens.json
if 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 configuration file output location using the CONFIG_PATH
environment variable:
The script handles paths intelligently:
- If
CONFIG_PATH
has no file extension, it's treated as a directory and.mongodb-lens.jsonc
is appended - If
CONFIG_PATH
ends with.json
(not.jsonc
), comments are automatically stripped from the output
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-connections
tool shows all available connection aliases
Note
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.
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 |
---|---|
mongoUri | CONFIG_MONGO_URI |
logLevel | CONFIG_LOG_LEVEL |
defaultDbName | CONFIG_DEFAULT_DB_NAME |
connectionOptions.maxPoolSize | CONFIG_CONNECTION_OPTIONS_MAX_POOL_SIZE |
connection.reconnectionRetries | CONFIG_CONNECTION_RECONNECTION_RETRIES |
defaults.queryLimit | CONFIG_DEFAULTS_QUERY_LIMIT |
tools.export.defaultFormat | CONFIG_TOOLS_EXPORT_DEFAULT_FORMAT |
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:Copy
- Prefix any NPX or Node.js environment variables in this document's examples:Copy
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
- macOS:
- 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
- Option 1: NPX (Recommended)
- Option 2: Docker Hub Image
- Option 3: Local Node.js Installation
- Option 4: Local Docker Image
For each option:
- Replace
mongodb://your-connection-string
with your MongoDB connection string or omit it to use the defaultmongodb://localhost:27017
. - To use a custom config file, set
CONFIG_PATH
environment variable. - To include environment variables:
- For NPX or Node.js add
"env": {}
with key-value pairs, for example:Copy - For Docker add
-e
flags, for example:Copy
- For NPX or Node.js add
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.
Note
MCP Inspector starts a proxy server on port 3000 and web client on port 5173.
Example NPX usage:
- Run MCP Inspector:Copy
- 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:
- Read-Only User Accounts
- Working with Database Backups
- Confirmation for Destructive Operations
- Disabling Destructive Operations
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: 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 userdrop-index
: Remove an index (potential performance impact)drop-database
: Permanently delete a databasedrop-collection
: Delete a collection and all its documentsdelete-document
: Delete one or multiple documentsbulk-operations
: When including delete operationsrename-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.
Note
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:
Warning
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:
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 permissionsdrop-index
: Removes indexes (can impact query performance)drop-database
: Permanently deletes entire databasesdrop-collection
: Permanently deletes collections and all their documentsdelete-document
: Removes documents matching specified criteriabulk-operations
: Can perform batch deletions when configured to do sorename-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 changestransaction
: Executes multiple operations in a transaction (potential for complex changes)modify-document
: Inserts or 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.
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:
- Start Sample Data Container
- Import Sample Data
- Connect MongoDB Lens
- Example Queries
- Working With Confirmation Protection
Tutorial: 1. Start Sample Data Container
Note
This tutorial assumes you have Docker installed and running on your system.
Important
If Docker is already running a container on port 27017, stop it before proceeding.
- Initialise the sample data container:Copy
- Verify the container is running without issue:Copy
Tutorial: 2. Import Sample Data
MongoDB provides several sample datasets which we'll use to explore MongoDB Lens.
- Download the sample datasets:Copy
- Copy the sample datasets into your sample data container:Copy
- Import the sample datasets into MongoDB:Copy
This will import several databases:
sample_airbnb
: Airbnb listings and reviewssample_analytics
: Customer and account datasample_geospatial
: Geographic datasample_mflix
: Movie datasample_restaurants
: Restaurant datasample_supplies
: Supply chain datasample_training
: Training data for various applicationssample_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
Tip
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
- Example Queries: Collection Management
- Example Queries: User Management
- Example Queries: Querying Data
- Example Queries: Schema Analysis
- Example Queries: Data Modification
- Example Queries: Performance & Index Management
- Example Queries: Geospatial & Special Operations
- Example Queries: Export, Administrative & Other Features
- Example Queries: Connection Management
Example Queries: Basic Database Operations
- "List all available databases"
➥ Uses list-databases
tool
- "What database am I currently using?"
➥ Uses current-database
tool
- "Switch to the sample_mflix database"
➥ Uses use-database
tool
- "Create a new database called test_db"
➥ Uses create-database
tool
- "Create another database called analytics_db and switch to it"
➥ Uses create-database
tool with switch=true
- "Drop the test_db database"
➥ Uses drop-database
tool (with confirmation)
Example Queries: Collection Management
- "What collections are in the current database?"
➥ Uses list-collections
tool
- "Create a new collection named user_logs"
➥ Uses create-collection
tool
- "Drop the user_logs collection"
➥ Uses drop-collection
tool (with confirmation)
- "Rename the user_logs collection to system_logs"
➥ Uses rename-collection
tool
- "Check the data consistency in the movies collection"
➥ Uses validate-collection
tool
Example Queries: User Management
- "Create a read-only user for analytics"
➥ Uses create-user
tool
- "Drop the inactive_user account"
➥ Uses drop-user
tool (with confirmation)
Example Queries: Querying Data
- "Count all documents in the movies collection"
➥ Uses count-documents
tool
- "Find the top 5 movies with the highest IMDB rating"
➥ Uses find-documents
tool
- "Show me aggregate data for movies grouped by decade"
➥ Uses aggregate-data
tool
- "List all unique countries where movies were produced"
➥ Uses distinct-values
tool
- "Search for movies containing 'godfather' in their title"
➥ Uses text-search
tool
- "Find German users with last name 'müller' using proper collation"
➥ Uses collation-query
tool
Example Queries: Schema Analysis
- "What's the schema structure of the movies collection?"
➥ Uses analyze-schema
tool
- "Compare the schema between users and comments collections"
➥ Uses compare-schemas
tool
- "Generate a JSON schema validator for the movies collection"
➥ Uses generate-schema-validator
tool
- "Analyze common query patterns for the movies collection"
➥ Uses analyze-query-patterns
tool
Example Queries: Data Modification
- "Insert a new movie document"
➥ Uses modify-document
tool (insert operation)
- "Update all movies from 1994 to add a 'classic' flag"
➥ Uses modify-document
tool (update operation)
- "Delete all movies with zero ratings"
➥ Uses delete-document
tool (with confirmation)
- "Run these bulk operations on the movies collection"
➥ Uses bulk-operations
tool
Example Queries: Performance & Index Management
- "Create an index on the title field in the movies collection"
➥ Uses create-index
tool
- "Drop the unused ratings_idx index"
➥ Uses drop-index
tool (with confirmation)
- "Explain the execution plan for finding movies from 1995"
➥ Uses explain-query
tool
- "Get statistics for the current database"
➥ Uses get-stats
tool (database target)
- "Show collection stats for the movies collection"
➥ Uses get-stats
tool (collection target)
Example Queries: Geospatial & Special Operations
- "Switch to sample_geospatial database, then find all shipwrecks within 10km of coordinates [-80.12, 26.46]"
➥ Uses geo-query
tool
- "Switch to sample_mflix database, then run this Map-Reduce to calculate movie counts by year with map
'function () { emit(this.year, 1) }'
and reduce'function (key, values) { return Array.sum(values) }'
"
➥ Uses map-reduce
tool
- "Switch to sample_analytics database, then execute a transaction to move funds between accounts"
➥ Uses transaction
tool
- "Create a time series collection for sensor readings"
➥ Uses create-timeseries
tool
- "Watch for changes in the users collection for 30 seconds"
➥ Uses watch-changes
tool
- "List all files in the images GridFS bucket"
➥ Uses gridfs-operation
tool (list operation)
Example Queries: Export, Administrative & Other Features
- "Switch to sample_mflix database, then export the top 20 movies based on 'tomatoes.critic.rating' as a CSV with title, year and rating fields, output as raw csv text in a single code block"
➥ Uses export-data
tool
- "Switch to sample_analytics database, then check its sharding status"
➥ Uses shard-status
tool
- "Switch to sample_weatherdata database, and generate an interactive report on its current state" ➥ Uses numerous tools
Example Queries: Connection Management
- "Connect to a different MongoDB server at mongodb://localhost:27018"
➥ Uses connect-mongodb
tool
- "Connect to MongoDB Atlas instance at mongodb+srv://username:password@cluster.mongodb.net/mydb"
➥ Uses connect-mongodb
tool
- "Connect back to the original MongoDB server"
➥ Uses connect-original
tool
- "Connect to a MongoDB replica set without validating the connection"
➥ Uses connect-mongodb
tool with validateConnection=false
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:Copy
- MongoDB Lens responds with a warning and confirmation token:Copy
- Confirm the operation by submitting the confirmation token:Copy
- MongoDB Lens executes the operation:Copy
This two-step process prevents accidental data loss by requiring explicit confirmation.
Note
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.
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
Full featured MCP Server for MongoDB database analysis.
- Contents
- Quick Start
- Features
- Installation
- Configuration
- Client Setup
- Data Protection
- Tutorial
- Disclaimer
- Support