mongodb lens
Full featured MCP Server for MongoDB database analysis.
Full featured MCP Server for MongoDB database analysis.
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.
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 collectionscollection-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 databaseaggregation-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 pipelinesMongoDB Lens includes numerous other features:
~/.mongodb-lens.[jsonc|json]
process.env.CONFIG_*
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.
{
"_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-collection
tool (with confirmation)MongoDB Lens can be installed and run in several ways:
[!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 withnpx
try runningnpx clear-npx-cache
prior to runningnpx -y mongodb-lens
(this clears the cache and re-downloads the package).
[!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
[!NOTE]
Node.js from source requires Node.js installed and running on your system (suggestion: use Volta).
git clone https://github.com/furey/mongodb-lens.git
cd /path/to/mongodb-lens
node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible
npm ci
# 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.
git clone https://github.com/furey/mongodb-lens.git
cd /path/to/mongodb-lens
docker --version # Ideally >= v27.x
docker build -t mongodb-lens .
# 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):
- admin (180.00 KB)
- config (108.00 KB)
- local (40.00 KB)
- sample_airbnb (51.88 MB)
- sample_analytics (9.46 MB)
- sample_geospatial (980.00 KB)
- sample_guides (40.00 KB)
- sample_mflix (108.90 MB)
- sample_restaurants (7.73 MB)
- sample_supplies (968.00 KB)
- sample_training (40.85 MB)
- sample_weatherdata (2.69 MB)"}]},"jsonrpc":"2.0","id":1}
MongoDB Lens is now installed and ready to accept MCP requests.
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
).
git clone https://github.com/furey/mongodb-lens.git
cd /path/to/mongodb-lens
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
...
}
npm install
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 backuseNewUrlParser
anduseUnifiedTopology
MongoDB configuration options.
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 [email protected]
Similarly for Docker:
docker run --rm -i --network=host furey/mongodb-lens:8.3.0
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:
mongodb://localhost:27017
mydatabase
with credentials from admin
database:mongodb://username:password@hostname:27017/mydatabase?authSource=admin
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.
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.
{
"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
"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.jsonc
first, then falls back to~/.mongodb-lens.json
if the former doesn't existTo 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
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
You can specify a custom output location using the CONFIG_PATH
environment variable.
CONFIG_PATH
has no file extension, it's treated as a directory an