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.
- Quick Start
- Features
- Installation
- Configuration
- Client Setup
- Data Protection
- Tutorial
- Disclaimer
- Support
- Install MongoDB Lens
- Configure MongoDB Lens
- Set up your MCP Client (e.g. Claude Desktop)
- Explore your MongoDB databases with natural language queries
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 collectionscount-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-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
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
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 patternsinspector-guide
: Get help using MongoDB Lens with MCP Inspectormigration-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: Overview
- Other Features: New Database Metadata
- Other Features: MongoDB Version Compatibility
MongoDB Lens includes several additional features:
- Sanitized Inputs: Security enhancements for query processing
- Configuration File: Custom configuration via
~/.mongodb-lens.json
- Connection Resilience: Automatic reconnection with exponential backoff
- JSONRPC Error Handling: Comprehensive error handling with proper error codes
- Memory Management: Automatic memory monitoring and cleanup for large operations
- Smart Caching: Enhanced caching for schemas, collection lists, and server status
When MongoDB Lens creates a new database via the create-database
tool, it automatically adds a metadata
collection containing a single document. This serves several purposes:
- MongoDB only persists databases containing at least one collection
- Records database creation details (timestamp, tool version, user)
- Captures environment information for diagnostics
Example metadata document
{
"_id" : ObjectId("67d5284463788ec38aecee14"),
"created" : {
"timestamp" : ISODate("2025-03-15T07:12:04.705Z"),
"tool" : "MongoDB Lens v5.0.7",
"user" : "anonymous"
},
"mongodb" : {
"version" : "3.6.23",
"connectionInfo" : {
"host" : "unknown",
"readPreference" : "primary"
}
},
"database" : {
"name" : "example_database",
"description" : "Created via MongoDB Lens"
},
"system" : {
"hostname" : "unknown",
"platform" : "darwin",
"nodeVersion" : "v22.14.0"
},
"lens" : {
"version" : "5.0.7",
"startTimestamp" : ISODate("2025-03-15T07:10:06.084Z")
}
}
You can safely remove this collection once you've added your own collections to the new database.
MongoDB Lens implements a backward compatibility layer to work reliably with both older MongoDB deployments and latest versions, providing consistent behavior without requiring version-specific configuration.
MongoDB Lens can be installed and run in several ways:
The easiest way to run MongoDB Lens is using npx
:
# Ensure Node.js is installed
node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible
# Using default connection string mongodb://localhost:27017
npx -y mongodb-lens
# Using custom connection string
npx -y mongodb-lens mongodb://your-connection-string
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).
Note
Docker Hub requires Docker installed and running on your system.
Run MongoDB Lens via Docker Hub:
# Using default connection string mongodb://localhost:27017
docker run --rm -i --network=host furey/mongodb-lens
# Using custom connection string
docker run --rm -i --network=host furey/mongodb-lens mongodb://your-connection-string
# Using "--pull" to keep the Docker image up-to-date
docker run --rm -i --network=host --pull=always furey/mongodb-lens
Note
Node.js from source requires Node.js installed and running on your system (suggestion: use Volta).
- 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
Note
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
- 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
To verify the installation, paste and run the following jsonrpc message into the server's stdio:
{"method":"resources/read","params":{"uri":"mongodb://databases"},"jsonrpc":"2.0","id":1}
The server should respond with a list of databases in your MongoDB instance, for example:
{"result":{"contents":[{"uri":"mongodb://databases","text":"Databases (12):\n- admin (180.00 KB)\n- config (108.00 KB)\n- local (40.00 KB)\n- sample_airbnb (51.88 MB)\n- sample_analytics (9.46 MB)\n- sample_geospatial (980.00 KB)\n- sample_guides (40.00 KB)\n- sample_mflix (108.90 MB)\n- sample_restaurants (7.73 MB)\n- sample_supplies (968.00 KB)\n- sample_training (40.85 MB)\n- sample_weatherdata (2.69 MB)"}]},"jsonrpc":"2.0","id":1}
MongoDB Lens is now installed and ready to accept MCP requests.
The server accepts a MongoDB connection string as its only argument.
Example NPX usage:
npx -y mongodb-lens mongodb://your-connection-string
MongoDB connection strings have the following format:
mongodb://[username:password@]host[:port][/database][?options]
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.
With verbose logging enabled, the server will output additional information to the console.
To enable verbose logging, set environment variable VERBOSE_LOGGING
to true
.
Example NPX usage:
VERBOSE_LOGGING=true npx -y mongodb-lens mongodb://your-connection-string
Example Docker Hub usage:
docker run --rm -i --network=host -e VERBOSE_LOGGING='true' furey/mongodb-lens mongodb://your-connection-string
MongoDB Lens can also be configured via JSON config file: ~/.mongodb-lens.json
Alternatively, set environment variable CONFIG_PATH
to the path of your custom config file.
Example NPX usage:
CONFIG_PATH='/path/to/config.json' npx -y mongodb-lens
Example Docker Hub usage:
docker run --rm -i --network=host -v /path/to/config.json:/root/.mongodb-lens.json furey/mongodb-lens
Example configuration file contents:
{
"mongoUri": "mongodb://username:password@hostname:27017/mydatabase?authSource=admin",
"connectionOptions": {
"maxPoolSize": 20,
"connectTimeoutMS": 30000
}
}
To use MongoDB Lens with Claude Desktop:
- Install Claude Desktop
- Open
claude_desktop_config.json
(create it 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
- 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
. - Set
VERBOSE_LOGGING
totrue
orfalse
. - To use a custom config file, see Configuration: Config File and adapt option accordingly.
{
"mcpServers": {
"mongodb-lens": {
"command": "/path/to/npx",
"args": [
"-y",
"mongodb-lens",
"mongodb://your-connection-string"
],
"env": {
"VERBOSE_LOGGING": "[true|false]"
}
}
}
}
{
"mcpServers": {
"mongodb-lens": {
"command": "docker",
"args": [
"run",
"--rm",
"-i",
"--network=host",
"--pull=always",
"-e",
"VERBOSE_LOGGING=[true|false]",
"furey/mongodb-lens",
"mongodb://your-connection-string"
]
}
}
}
{
"mcpServers": {
"mongodb-lens": {
"command": "/path/to/node",
"args": [
"/path/to/mongodb-lens.js",
"mongodb://your-connection-string"
],
"env": {
"VERBOSE_LOGGING": "[true|false]"
}
}
}
}
{
"mcpServers": {
"mongodb-lens": {
"command": "docker",
"args": [
"run",
"--rm",
"-i",
"--network=host",
"-e",
"VERBOSE_LOGGING=[true|false]",
"mongodb-lens",
"mongodb://your-connection-string"
]
}
}
}
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:
# Using default connection string mongodb://localhost:27017 npx -y @modelcontextprotocol/inspector npx -y mongodb-lens # Using custom connection string npx -y @modelcontextprotocol/inspector npx -y mongodb-lens mongodb://your-connection-string # Using verbose logging npx -y @modelcontextprotocol/inspector -e VERBOSE_LOGGING=true npx -y mongodb-lens # Using custom ports SERVER_PORT=1234 CLIENT_PORT=5678 npx -y @modelcontextprotocol/inspector npx -y mongodb-lens
- 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
MongoDB Lens should be usable with any MCP-compatible client.
For more, see: MCP Documentation: Example Clients
To protect your data while using MongoDB Lens, consider the following:
When connecting MongoDB Lens to your database, the permissions granted to the user in your connection string dictate what actions can be performed. For exploration and analysis, 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:
use admin
db.createUser({
user: 'readonly',
pwd: 'eXaMpLePaSsWoRd',
roles: [{ role: 'read', db: 'mydatabase' }]
})
Then, plug those credentials into your MongoDB Lens connection string (e.g. mongodb://readonly:eXaMpLePaSsWoRd@localhost:27017/mydatabase
). This restricts MongoDB Lens to read-only operations, safeguarding your data during development or testing. It's a simple yet effective way to enforce security boundaries, especially when you're poking around schemas or running ad-hoc queries.
To keep your production data unmodified while leveraging MongoDB Lens for analysis, its suggested to use a backup copy hosted on a separate MongoDB instance. This setup isolates your live environment, letting you experiment with queries or aggregations without risking accidental corruption.
Start by generating a 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 operationsβlike pipeline-heavy aggregations or schema tweaksβwithout touching your production data. It's a practical choice when you need to dig into your dataset safely, especially in scenarios where live modifications aren't an option.
MongoDB Lens implements a token-based confirmation system for potentially destructive operations. This system requires a two-step process for executing commands that could result in data loss:
- First command invocation: Returns a 4-digit confirmation token that expires after 5 minutes
- Second command invocation: Executes the operation if provided with the valid token
Operations that require confirmation include:
bulk-operations
: When including delete operationsdelete-document
: Delete one or multiple documentsdrop-collection
: Delete a collection and all its documentsdrop-database
: Permanently delete a databasedrop-index
: Remove an index (potential performance impact)drop-user
: Remove a database userrename-collection
: When the target collection exists and will be dropped
This protection mechanism prevents 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.
You might want to bypass the token confirmation system.
Set the environment variable DISABLE_DESTRUCTIVE_OPERATION_TOKENS
to true
to execute destructive operations immediately without confirmation:
# Using NPX
DISABLE_DESTRUCTIVE_OPERATION_TOKENS=true npx -y mongodb-lens
# Using Docker
docker run --rm -i --network=host -e DISABLE_DESTRUCTIVE_OPERATION_TOKENS='true' furey/mongodb-lens
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.
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
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:
docker run --name mongodb-sampledata -d -p 27017:27017 mongo:6
- Verify the container is running without issue:
docker ps | grep mongodb-sampledata
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 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
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:
{
"mcpServers": {
"mongodb-lens": {
"command": "/path/to/npx",
"args": [
"-y",
"mongodb-lens"
]
}
}
}
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
- "List all available databases"
β₯ Useslist-databases
tool - "What database am I currently using?"
β₯ Usescurrent-database
tool - "Switch to the sample_mflix database"
β₯ Usesuse-database
tool - "Create a new database called test_db"
β₯ Usescreate-database
tool - "Create another database called analytics_db and switch to it"
β₯ Usescreate-database
tool with switch=true - "Drop the test_db database"
β₯ Usesdrop-database
tool - "Drop test_db with token 1234"
β₯ Usesdrop-database
tool (with token)
- "What collections are in the current database?"
β₯ Useslist-collections
tool - "Create a new collection named user_logs"
β₯ Usescreate-collection
tool - "Drop the user_logs collection"
β₯ Usesdrop-collection
tool - "Drop user_logs collection with token 5678"
β₯ Usesdrop-collection
tool (with token) - "Rename the user_logs collection to system_logs"
β₯ Usesrename-collection
tool - "Check the data consistency in the movies collection"
β₯ Usesvalidate-collection
tool
- "Create a read-only user for analytics"
β₯ Usescreate-user
tool - "Drop the inactive_user account"
β₯ Usesdrop-user
tool - "Drop inactive_user with token 7890"
β₯ Usesdrop-user
tool (with token)
- "Count all documents in the movies collection"
β₯ Usescount-documents
tool - "Find the top 5 movies with the highest IMDB rating"
β₯ Usesfind-documents
tool - "Show me aggregate data for movies grouped by decade"
β₯ Usesaggregate-data
tool - "List all unique countries where movies were produced"
β₯ Usesdistinct-values
tool - "Search for movies containing 'godfather' in their title"
β₯ Usestext-search
tool - "Find German users with last name 'mΓΌller' using proper collation"
β₯ Usescollation-query
tool
- "What's the schema structure of the movies collection?"
β₯ Usesanalyze-schema
tool - "Compare the schema between users and comments collections"
β₯ Usescompare-schemas
tool - "Generate a JSON schema validator for the movies collection"
β₯ Usesgenerate-schema-validator
tool - "Analyze common query patterns for the movies collection"
β₯ Usesanalyze-query-patterns
tool
- "Insert a new movie document"
β₯ Usesmodify-document
tool (insert operation) - "Update all movies from 1994 to add a 'classic' flag"
β₯ Usesmodify-document
tool (update operation) - "Delete all movies with zero ratings"
β₯ Usesdelete-document
tool - "Delete movies with zero ratings using token 9012"
β₯ Usesdelete-document
tool (with token) - "Run these bulk operations on the movies collection"
β₯ Usesbulk-operations
tool
- "Create an index on the title field in the movies collection"
β₯ Usescreate-index
tool - "Drop the unused ratings_idx index"
β₯ Usesdrop-index
tool - "Drop the ratings_idx index with token 3456"
β₯ Usesdrop-index
tool (with token) - "Explain the execution plan for finding movies from 1995"
β₯ Usesexplain-query
tool - "Get statistics for the current database"
β₯ Usesget-stats
tool (database target) - "Show collection stats for the movies collection"
β₯ Usesget-stats
tool (collection target)
- "Switch to sample_geospatial database, then find all shipwrecks within 10km of coordinates [-80.12, 26.46]"
β₯ Usesgeo-query
tool - "Switch to sample_mflix database, then run this MapReduce to calculate movie counts by year with map function 'function() { emit(this.year, 1); }' and reduce function 'function(key, values) { return Array.sum(values); }'"
β₯ Usesmap-reduce
tool - "Switch to sample_analytics database, then execute a transaction to move funds between accounts"
β₯ Usestransaction
tool - "Create a time series collection for sensor readings"
β₯ Usescreate-timeseries
tool - "Watch for changes in the users collection for 30 seconds"
β₯ Useswatch-changes
tool - "List all files in the images GridFS bucket"
β₯ Usesgridfs-operation
tool (list operation)
- "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"
β₯ Usesexport-data
tool - "Switch to sample_analytics database, then check its sharding status"
β₯ Usesshard-status
tool - "Switch to sample_weatherdata database, and generate an interactive report on its current state"
β₯ Uses numerous tools
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 including the confirmation token:
"Drop test_collection with token 1234"
- MongoDB Lens executes the operation:
Collection 'test_collection' has been permanently deleted.
This two-step process prevents accidental data loss by requiring explicit confirmation.
For development environments, this can be bypassed by setting the DISABLE_DESTRUCTIVE_OPERATION_TOKENS
environment variable to true
.
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.
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.