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
- Features
- Installation
- Configuration
- Client Setup
- Data Protection
- Tutorial
- Test Suite
- Disclaimer
- Support
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
- Resources
- Prompts
- Other
Tools
add-connection-alias: Add a new MongoDB connection aliasaggregate-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)clear-cache: Clear memory caches to ensure fresh datacollation-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 bucketsinsert-document: Insert one or more documents into collectionslist-collections: Explore collections in the current databaselist-connections: View all available MongoDB connection aliaseslist-databases: View all accessible databasesrename-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 transactionupdate-document: Update documents matching specified criteriause-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
- Overview
- New Database Metadata
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.
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")
}
}
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"
➥ Usesdrop-collectiontool (with confirmation)
Installation
MongoDB Lens can be installed and run in several ways:
- NPX (Easiest)
- Docker Hub
- Node.js from Source
- Docker from Source
- Installation Verification
- Older MongoDB Versions
Installation: NPX
[!NOTE]
NPX requires Node.js installed and running on your system (suggestion: use Volta).
The easiest way to run MongoDB Lens is using NPX.
First, ensure Node.js is installed:
node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible
Then, run MongoDB Lens via NPX:
# Using default connection string mongodb://localhost:27017
npx -y mongodb-lens
# Using custom connection string
npx -y mongodb-lens mongodb://your-connection-string
# Using "@latest" to keep the package up-to-date
npx -y mongodb-lens@latest
[!TIP]
If you encounter permissions errors withnpxtry runningnpx clear-npx-cacheprior to runningnpx -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:
docker --version # Ideally >= v27.x
Then, 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
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:
git clone https://github.com/furey/mongodb-lens.gitNavigate to the cloned repository directory:
cd /path/to/mongodb-lensEnsure Node.js is installed:
node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatibleInstall Node.js dependencies:
npm ciStart 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
[!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.gitNavigate to the cloned repository directory:
cd /path/to/mongodb-lensEnsure Docker is installed:
docker --version # Ideally >= v27.xBuild 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:
{"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.
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.gitNavigate to the cloned repository directory:
cd /path/to/mongodb-lensModify
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 installStart MongoDB Lens:
node mongodb-lens.js mongodb://older-mongodb-instance
This will use the older driver version compatible with your MongoDB instance.
[!NOTE]
You may also need to revert this commit to add backuseNewUrlParseranduseUnifiedTopologyMongoDB 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:
npx -y mongodb-lens@8.3.0
Similarly for Docker:
docker run --rm -i --network=host furey/mongodb-lens:8.3.0
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:
npx -y mongodb-lens@latest 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
mydatabasewith credentials fromadmindatabase:
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.
[!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.jsonand.jsonc(JSON with comments) config file formats.
Example configuration file
{
"mongoUri": "mongodb://localhost:27017", // Default MongoDB connection string or object of alias-URI pairs
"connectionOptions": {
"maxPoolSize": 20, // Maximum number of connections in the pool
"retryWrites": false, // Whether to retry write operations
"connectTimeoutMS": 30000, // Connection timeout in milliseconds
"socketTimeoutMS": 360000, // Socket timeout in milliseconds
"heartbeatFrequencyMS": 10000, // How often to ping servers for status
"serverSelectionTimeoutMS": 30000 // Timeout for server selection
},
"defaultDbName": "admin", // Default database if not specified in URI
"connection": {
"maxRetries": 5, // Maximum number of initial connection attempts
"maxRetryDelayMs": 30000, // Maximum delay between retries
"reconnectionRetries": 10, // Maximum reconnection attempts if connection lost
"initialRetryDelayMs": 1000 // Initial delay between retries
},
"disabled": {
"tools": [], // Array of tools to disable or true to disable all
"prompts": [], // Array of prompts to disable or true to disable all
"resources": [] // Array of resources to disable or true to disable all
},
"enabled": {
"tools": true, // Array of tools to enable or true to enable all
"prompts": true, // Array of prompts to enable or true to enable all
"resources": true // Array of resources to enable or true to enable all
},
"cacheTTL": {
"stats": 15000, // Stats cache lifetime in milliseconds
"fields": 30000, // Fields cache lifetime in milliseconds
"schemas": 60000, // Schema cache lifetime in milliseconds
"indexes": 120000, // Index cache lifetime in milliseconds
"collections": 30000, // Collections list cache lifetime in milliseconds
"serverStatus": 20000 // Server status cache lifetime in milliseconds
},
"enabledCaches": [ // List of caches to enable
"stats", // Statistics cache
"fields", // Collection fields cache
"schemas", // Collection schemas cache
"indexes", // Collection indexes cache
"collections", // Database collections cache
"serverStatus" // MongoDB server status cache
],
"memory": {
"enableGC": true, // Whether to enable garbage collection
"warningThresholdMB": 1500, // Memory threshold for warnings
"criticalThresholdMB": 2000 // Memory threshold for cache clearing
},
"logLevel": "info", // Log level (info or verbose)
"disableDestructiveOperationTokens": false, // Whether to skip confirmation for destructive ops
"readOnly": false, // Whether to block tools and pipeline stages that write
"watchdogIntervalMs": 30000, // Interval for connection monitoring
"defaults": {
"slowMs": 100, // Threshold for slow query detection
"queryLimit": 10, // Default limit for query results
"allowDiskUse": true, // Allow operations to use disk for large datasets
"schemaSampleSize": 100, // Sample size for schema inference
"aggregationBatchSize": 50 // Batch size for aggregation operations
},
"security": {
"tokenLength": 4, // Length of confirmation tokens
"tokenExpirationMinutes": 5, // Expiration time for tokens
"strictDatabaseNameValidation": true // Enforce strict database name validation
},
"tools": {
"transaction": {
"readConcern": "snapshot", // Read concern level for transactions
"writeConcern": {
"w": "majority" // Write concern for transactions
}
},
"bulkOperations": {
"ordered": true // Whether bulk operations execute in order
},
"export": {
"defaultLimit": -1, // Default limit for exports (-1 = no limit)
"defaultFormat": "json" // Default export format (json or csv)
},
"watchChanges": {
"maxDurationSeconds": 60, // Maximum duration for change streams
"defaultDurationSeconds": 10 // Default duration for change streams
},
"queryAnalysis": {
"defaultDurationSeconds": 10 // Default duration for query analysis
}
}
}
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:
CONFIG_PATH='/path/to/config.json' npx -y mongodb-lens@latest
Example Docker Hub usage:
docker run --rm -i --network=host --pull=always -v /path/to/config.json:/root/.mongodb-lens.json furey/mongodb-lens
Configuration: Config File Generation
You can generate a configuration file automatically using the config:create script:
# NPX Usage (recommended)
npx -y mongodb-lens@latest config:create
# Node.js Usage
npm run config:create
# Force overwrite existing files
npx -y mongodb-lens@latest config:create -- --force
npm run config:create -- --force
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:
# With custom path
CONFIG_PATH=/path/to/config.jsonc npx -y mongodb-lens@latest config:create
# Save to directory (will append .mongodb-lens.jsonc to the path)
CONFIG_PATH=/path/to/directory npx -y mongodb-lens@latest config:create
# Save as JSON instead of JSONC
CONFIG_PATH=/path/to/config.json npx -y mongodb-lens@latest config:create
Example Node.js usage:
# With custom path
CONFIG_PATH=/path/to/config.jsonc node mongodb-lens.js config:create
# Save to directory (will append .mongodb-lens.jsonc to the path)
CONFIG_PATH=/path/to/directory node mongodb-lens.js config:create
# Save as JSON instead of JSONC
CONFIG_PATH=/path/to/config.json node mongodb-lens.js config:create
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:
{
"mongoUri": {
"main": "mongodb://localhost:27017",
"backup": "mongodb://localhost:27018",
"atlas": "mongodb+srv://username:password@cluster.mongodb.net/mydb"
}
}
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
[!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.
[!TIP]
To add connection aliases at runtime, use theadd-connection-aliastool.
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:
CONFIG_[SETTING PATH, SNAKE CASED, UPPERCASED]
Example overrides:
| Config Setting | Environment Variable Override |
|---|---|
mongoUri |
CONFIG_MONGO_URI |
logLevel |
CONFIG_LOG_LEVEL |
defaultDbName |
CONFIG_DEFAULT_DB_NAME |
defaults.queryLimit |
CONFIG_DEFAULTS_QUERY_LIMIT |
tools.export.defaultFormat |
CONFIG_TOOLS_EXPORT_DEFAULT_FORMAT |
connectionOptions.maxPoolSize |
CONFIG_CONNECTION_OPTIONS_MAX_POOL_SIZE |
connection.reconnectionRetries |
CONFIG_CONNECTION_RECONNECTION_RETRIES |
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:
CONFIG_DEFAULTS_QUERY_LIMIT='25' npx -y mongodb-lens@latest
Example Docker Hub usage:
docker run --rm -i --network=host --pull=always -e CONFIG_DEFAULTS_QUERY_LIMIT='25' furey/mongodb-lens
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-envPrefix 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