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 - Installation - Configuration - Client Setup - Data Protection - Test Suite - Disclaimer - Install MongoDB Lens - Configure MongoDB Lens - Set up your MCP Client (e.g. Claude D
Add this skill
npx mdskills install furey/mongodb-lensComprehensive MCP server for MongoDB with extensive tools, resources, and good documentation
1# MongoDB Lens23[](./LICENSE)4[](https://hub.docker.com/r/furey/mongodb-lens)5[](https://www.npmjs.com/package/mongodb-lens)6[](https://www.buymeacoffee.com/furey)78**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.910## Contents1112- [Quick Start](#quick-start)13- [Features](#features)14- [Installation](#installation)15- [Configuration](#configuration)16- [Client Setup](#client-setup)17- [Data Protection](#data-protection)18- [Tutorial](#tutorial)19- [Test Suite](#test-suite)20- [Disclaimer](#disclaimer)21- [Support](#support)2223## Quick Start2425- [Install](#installation) MongoDB Lens26- [Configure](#configuration) MongoDB Lens27- [Set up](#client-setup) your MCP Client (e.g. [Claude Desktop](#client-setup-claude-desktop), [Cursor](https://docs.cursor.com/context/model-context-protocol#configuring-mcp-servers), etc)28- Explore your MongoDB databases with [natural language queries](#tutorial-4-example-queries)2930## Features3132- [Tools](#tools)33- [Resources](#resources)34- [Prompts](#prompts)35- [Other](#other-features)3637### Tools3839- [`add-connection-alias`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27add-connection-alias%27%2C%2F): Add a new MongoDB connection alias40- [`aggregate-data`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27aggregate-data%27%2C%2F): Execute aggregation pipelines41- [`analyze-query-patterns`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27analyze-query-patterns%27%2C%2F): Analyze live queries and suggest optimizations42- [`analyze-schema`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27analyze-schema%27%2C%2F): Automatically infer collection schemas43- [`bulk-operations`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27bulk-operations%27%2C%2F): Perform multiple operations efficiently ([requires confirmation](#data-protection-confirmation-for-destructive-operations) for destructive operations)44- [`clear-cache`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27clear-cache%27%2C%2F): Clear memory caches to ensure fresh data45- [`collation-query`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27collation-query%27%2C%2F): Find documents with language-specific collation rules46- [`compare-schemas`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27compare-schemas%27%2C%2F): Compare schemas between two collections47- [`connect-mongodb`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27connect-mongodb%27%2C%2F): Connect to a different MongoDB URI48- [`connect-original`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27connect-original%27%2C%2F): Connect back to the original MongoDB URI used at startup49- [`count-documents`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27count-documents%27%2C%2F): Count documents matching specified criteria50- [`create-collection`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27create-collection%27%2C%2F): Create new collections with custom options51- [`create-database`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27create-database%27%2C%2F): Create a new database with option to switch to it52- [`create-index`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27create-index%27%2C%2F): Create new indexes for performance optimization53- [`create-timeseries`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27create-timeseries%27%2C%2F): Create time series collections for temporal data54- [`create-user`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27create-user%27%2C%2F): Create new database users with specific roles55- [`current-database`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27current-database%27%2C%2F): Show the current database context56- [`delete-document`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27delete-document%27%2C%2F): Delete documents matching specified criteria ([requires confirmation](#data-protection-confirmation-for-destructive-operations))57- [`distinct-values`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27distinct-values%27%2C%2F): Extract unique values for any field58- [`drop-collection`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27drop-collection%27%2C%2F): Remove collections from the database ([requires confirmation](#data-protection-confirmation-for-destructive-operations))59- [`drop-database`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27drop-database%27%2C%2F): Drop a database ([requires confirmation](#data-protection-confirmation-for-destructive-operations))60- [`drop-index`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27drop-index%27%2C%2F): Remove indexes from collections ([requires confirmation](#data-protection-confirmation-for-destructive-operations))61- [`drop-user`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27drop-user%27%2C%2F): Remove database users ([requires confirmation](#data-protection-confirmation-for-destructive-operations))62- [`explain-query`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27explain-query%27%2C%2F): Analyze query execution plans63- [`export-data`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27export-data%27%2C%2F): Export query results in JSON or CSV format64- [`find-documents`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27find-documents%27%2C%2F): Run queries with filters, projections, and sorting65- [`generate-schema-validator`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27generate-schema-validator%27%2C%2F): Generate JSON Schema validators66- [`geo-query`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27geo-query%27%2C%2F): Perform geospatial queries with various operators67- [`get-stats`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27get-stats%27%2C%2F): Retrieve database or collection statistics68- [`gridfs-operation`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27gridfs-operation%27%2C%2F): Manage large files with GridFS buckets69- [`insert-document`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27insert-document%27%2C%2F): Insert one or more documents into collections70- [`list-collections`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27list-collections%27%2C%2F): Explore collections in the current database71- [`list-connections`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27list-connections%27%2C%2F): View all available MongoDB connection aliases72- [`list-databases`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27list-databases%27%2C%2F): View all accessible databases73- [`rename-collection`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27rename-collection%27%2C%2F): Rename existing collections ([requires confirmation](#data-protection-confirmation-for-destructive-operations) when dropping targets)74- [`shard-status`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27shard-status%27%2C%2F): View sharding configuration for databases and collections75- [`text-search`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27text-search%27%2C%2F): Perform full-text search across text-indexed fields76- [`transaction`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27transaction%27%2C%2F): Execute multiple operations in a single ACID transaction77- [`update-document`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27update-document%27%2C%2F): Update documents matching specified criteria78- [`use-database`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27use-database%27%2C%2F): Switch to a specific database context79- [`validate-collection`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27validate-collection%27%2C%2F): Check for data inconsistencies80- [`watch-changes`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27watch-changes%27%2C%2F): Monitor real-time changes to collections8182### Resources8384- [`collection-indexes`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.resource%5C%28%5Cs*%27collection-indexes%27%2C%2F): Index information for a collection85- [`collection-schema`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.resource%5C%28%5Cs*%27collection-schema%27%2C%2F): Schema information for a collection86- [`collection-stats`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.resource%5C%28%5Cs*%27collection-stats%27%2C%2F): Performance statistics for a collection87- [`collection-validation`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.resource%5C%28%5Cs*%27collection-validation%27%2C%2F): Validation rules for a collection88- [`collections`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.resource%5C%28%5Cs*%27collections%27%2C%2F): List of collections in the current database89- [`database-triggers`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.resource%5C%28%5Cs*%27database-triggers%27%2C%2F): Database change streams and event triggers configuration90- [`database-users`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.resource%5C%28%5Cs*%27database-users%27%2C%2F): Database users and roles in the current database91- [`databases`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.resource%5C%28%5Cs*%27databases%27%2C%2F): List of all accessible databases92- [`performance-metrics`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.resource%5C%28%5Cs*%27performance-metrics%27%2C%2F): Real-time performance metrics and profiling data93- [`replica-status`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.resource%5C%28%5Cs*%27replica-status%27%2C%2F): Replica set status and configuration94- [`server-status`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.resource%5C%28%5Cs*%27server-status%27%2C%2F): Server status information95- [`stored-functions`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.resource%5C%28%5Cs*%27stored-functions%27%2C%2F): Stored JavaScript functions in the current database9697### Prompts9899- [`aggregation-builder`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.prompt%5C%28%5Cs*%27aggregation-builder%27%2C%2F): Step-by-step creation of aggregation pipelines100- [`backup-strategy`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.prompt%5C%28%5Cs*%27backup-strategy%27%2C%2F): Customized backup and recovery recommendations101- [`data-modeling`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.prompt%5C%28%5Cs*%27data-modeling%27%2C%2F): Expert advice on MongoDB schema design for specific use cases102- [`database-health-check`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.prompt%5C%28%5Cs*%27database-health-check%27%2C%2F): Comprehensive database health assessment and recommendations103- [`index-recommendation`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.prompt%5C%28%5Cs*%27index-recommendation%27%2C%2F): Get personalized index suggestions based on query patterns104- [`migration-guide`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.prompt%5C%28%5Cs*%27migration-guide%27%2C%2F): Step-by-step MongoDB version migration plans105- [`mongo-shell`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.prompt%5C%28%5Cs*%27mongo-shell%27%2C%2F): Generate MongoDB shell commands with explanations106- [`multi-tenant-design`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.prompt%5C%28%5Cs*%27multi-tenant-design%27%2C%2F): Design MongoDB multi-tenant database architecture107- [`query-builder`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.prompt%5C%28%5Cs*%27query-builder%27%2C%2F): Interactive guidance for constructing MongoDB queries108- [`query-optimizer`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.prompt%5C%28%5Cs*%27query-optimizer%27%2C%2F): Optimization recommendations for slow queries109- [`schema-analysis`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.prompt%5C%28%5Cs*%27schema-analysis%27%2C%2F): Detailed collection schema analysis with recommendations110- [`schema-versioning`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.prompt%5C%28%5Cs*%27schema-versioning%27%2C%2F): Manage schema evolution in MongoDB applications111- [`security-audit`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.prompt%5C%28%5Cs*%27security-audit%27%2C%2F): Database security analysis and improvement recommendations112- [`sql-to-mongodb`](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.prompt%5C%28%5Cs*%27sql-to-mongodb%27%2C%2F): Convert SQL queries to MongoDB aggregation pipelines113114### Other Features115116- [Overview](#other-features-overview)117- [New Database Metadata](#other-features-new-database-metadata)118119#### Other Features: Overview120121MongoDB Lens includes numerous other features:122123- **[Config File](#configuration-config-file)**: Custom configuration via `~/.mongodb-lens.[jsonc|json]`124- **[Env Var Overrides](#configuration-environment-variable-overrides)**: Override config settings via `process.env.CONFIG_*`125- **[Confirmation System](#data-protection-confirmation-for-destructive-operations)**: Two-step verification for destructive operations126- **[Multiple Connections](#configuration-multiple-mongodb-connections)**: Define and switch between named URI aliases127- **[Component Disabling](#disabling-tools)**: Selectively disable tools, prompts or resources128- **Connection Resilience**: Auto-reconnection with exponential backoff129- **Query Safeguards**: Configurable limits and performance protections130- **Error Handling**: Comprehensive JSONRPC error codes and messages131- **Schema Inference**: Efficient schema analysis with intelligent sampling132- **Credential Protection**: Connection string password obfuscation in logs133- **Memory Management**: Auto-monitoring and cleanup for large operations134- **Smart Caching**: Optimized caching for schema, indexes, fields and collections135- **Backwards Compatible**: Support both modern and legacy MongoDB versions136137#### Other Features: New Database Metadata138139MongoDB Lens inserts a `metadata` collection into each database it creates.140141This `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.142143<details>144 <summary><strong>Example metadata document</strong></summary>145146```js147{148 "_id" : ObjectId("67d5284463788ec38aecee14"),149 "created" : {150 "timestamp" : ISODate("2025-03-15T07:12:04.705Z"),151 "tool" : "MongoDB Lens v5.0.7",152 "user" : "anonymous"153 },154 "mongodb" : {155 "version" : "3.6.23",156 "connectionInfo" : {157 "host" : "unknown",158 "readPreference" : "primary"159 }160 },161 "database" : {162 "name" : "example_database",163 "description" : "Created via MongoDB Lens"164 },165 "system" : {166 "hostname" : "unknown",167 "platform" : "darwin",168 "nodeVersion" : "v22.14.0"169 },170 "lens" : {171 "version" : "5.0.7",172 "startTimestamp" : ISODate("2025-03-15T07:10:06.084Z")173 }174}175```176177</details>178179Once you've added your own collections to your new database, you can safely remove the `metadata` collection via the `drop-collection` tool:180181- _"Drop the new database's metadata collection"_<br>182 <sup>➥ Uses `drop-collection` tool (with confirmation)</sup>183184## Installation185186MongoDB Lens can be installed and run in several ways:187188- [NPX](#installation-npx) (Easiest)189- [Docker Hub](#installation-docker-hub)190- [Node.js from Source](#installation-nodejs-from-source)191- [Docker from Source](#installation-docker-from-source)192- [Installation Verification](#installation-verification)193- [Older MongoDB Versions](#installation-older-mongodb-versions)194195### Installation: NPX196197> [!NOTE]<br>198> NPX requires [Node.js](https://nodejs.org/en/download) installed and running on your system (suggestion: use [Volta](https://volta.sh)).199200The easiest way to run MongoDB Lens is using NPX.201202First, ensure Node.js is installed:203204```console205node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible206```207208Then, run MongoDB Lens via NPX:209210```console211# Using default connection string mongodb://localhost:27017212npx -y mongodb-lens213214# Using custom connection string215npx -y mongodb-lens mongodb://your-connection-string216217# Using "@latest" to keep the package up-to-date218npx -y mongodb-lens@latest219```220221> [!TIP]<br>222> 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).223224### Installation: Docker Hub225226> [!NOTE]<br>227> Docker Hub requires [Docker](https://docs.docker.com/get-started/get-docker) installed and running on your system.228229First, ensure Docker is installed:230231```console232docker --version # Ideally >= v27.x233```234235Then, run MongoDB Lens via Docker Hub:236237```console238# Using default connection string mongodb://localhost:27017239docker run --rm -i --network=host furey/mongodb-lens240241# Using custom connection string242docker run --rm -i --network=host furey/mongodb-lens mongodb://your-connection-string243244# Using "--pull" to keep the Docker image up-to-date245docker run --rm -i --network=host --pull=always furey/mongodb-lens246```247248### Installation: Node.js from Source249250> [!NOTE]<br>251> Node.js from source requires [Node.js](https://nodejs.org/en/download) installed and running on your system (suggestion: use [Volta](https://volta.sh)).2522531. Clone the MongoDB Lens repository:<br>254 ```console255 git clone https://github.com/furey/mongodb-lens.git256 ```2571. Navigate to the cloned repository directory:<br>258 ```console259 cd /path/to/mongodb-lens260 ```2611. Ensure Node.js is installed:<br>262 ```console263 node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible264 ```2651. Install Node.js dependencies:<br>266 ```console267 npm ci268 ```2691. Start the server:<br>270 ```console271 # Using default connection string mongodb://localhost:27017272 node mongodb-lens.js273274 # Using custom connection string275 node mongodb-lens.js mongodb://your-connection-string276 ```277278### Installation: Docker from Source279280> [!NOTE]<br>281> Docker from source requires [Docker](https://docs.docker.com/get-started/get-docker) installed and running on your system.2822831. Clone the MongoDB Lens repository:<br>284 ```console285 git clone https://github.com/furey/mongodb-lens.git286 ```2871. Navigate to the cloned repository directory:<br>288 ```console289 cd /path/to/mongodb-lens290 ```2911. Ensure Docker is installed:<br>292 ```console293 docker --version # Ideally >= v27.x294 ```2951. Build the Docker image:<br>296 ```console297 docker build -t mongodb-lens .298 ```2991. Run the container:<br>300 ```console301 # Using default connection string mongodb://localhost:27017302 docker run --rm -i --network=host mongodb-lens303304 # Using custom connection string305 docker run --rm -i --network=host mongodb-lens mongodb://your-connection-string306 ```307308### Installation Verification309310To verify the installation, paste and run the following JSONRPC message into the server's stdio:311312```json313{"method":"resources/read","params":{"uri":"mongodb://databases"},"jsonrpc":"2.0","id":1}314```315316The server should respond with a list of databases in your MongoDB instance, for example:317318```json319{"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}320```321322MongoDB Lens is now installed and ready to accept MCP requests.323324### Installation: Older MongoDB Versions325326If 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.327328To 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`).329330#### Older MongoDB Versions: Running from Source3313321. Clone the MongoDB Lens repository:<br>333 ```console334 git clone https://github.com/furey/mongodb-lens.git335 ```3361. Navigate to the cloned repository directory:<br>337 ```console338 cd /path/to/mongodb-lens339 ```3401. Modify `package.json`:<br>341 ```diff342 "dependencies": {343 ...344 - "mongodb": "^6.15.0", // Or whatever newer version is listed345 + "mongodb": "^3.7.4", // Or whatever 3.x version is compatible with your older MongoDB instance346 ...347 }348 ```3491. Install Node.js dependencies:<br>350 ```console351 npm install352 ```3531. Start MongoDB Lens:<br>354 ```console355 node mongodb-lens.js mongodb://older-mongodb-instance356 ```357358This will use the older driver version compatible with your MongoDB instance.359360> [!NOTE]<br>361> You may also need to revert [this commit](https://github.com/furey/mongodb-lens/commit/603b28cbde72fcd62a15cd324afc93028380a054) to add back `useNewUrlParser` and `useUnifiedTopology` MongoDB configuration options.362363#### Older MongoDB Versions: Using NPX or Docker364365If 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.366367For example, MongoDB Lens `8.3.0` uses MongoDB Node.js driver `3.7.4` (see: [`package-lock.json`](https://github.com/furey/mongodb-lens/blob/8.3.0/package-lock.json#L944-L945)).368369To run an older version of MongoDB Lens using NPX, specify the version tag:370371```console372npx -y mongodb-lens@8.3.0373```374375Similarly for Docker:376377```console378docker run --rm -i --network=host furey/mongodb-lens:8.3.0379```380381## Configuration382383- [MongoDB Connection String](#configuration-mongodb-connection-string)384- [Config File](#configuration-config-file)385- [Config File Generation](#configuration-config-file-generation)386- [Multiple MongoDB Connections](#configuration-multiple-mongodb-connections)387- [Environment Variable Overrides](#configuration-environment-variable-overrides)388- [Cross-Platform Environment Variables](#configuration-cross-platform-environment-variables)389390### Configuration: MongoDB Connection String391392The server accepts a MongoDB connection string as its only argument.393394Example NPX usage:395396```console397npx -y mongodb-lens@latest mongodb://your-connection-string398```399400MongoDB connection strings have the following format:401402```txt403mongodb://[username:password@]host[:port][/database][?options]404```405406Example connection strings:407408- Local connection:<br>409 `mongodb://localhost:27017`410- Connection to `mydatabase` with credentials from `admin` database:<br>411 `mongodb://username:password@hostname:27017/mydatabase?authSource=admin`412- Connection to `mydatabase` with various other options:<br>413 `mongodb://hostname:27017/mydatabase?retryWrites=true&w=majority`414415If no connection string is provided, the server will attempt to connect via local connection.416417### Configuration: Config File418419MongoDB Lens supports extensive customization via JSON configuration file.420421> [!NOTE]<br>422> The config file is optional. MongoDB Lens will run with default settings if no config file is provided.423424> [!TIP]<br>425> 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.426427> [!TIP]<br>428> MongoDB Lens supports both `.json` and `.jsonc` (JSON with comments) config file formats.429430<details>431 <summary><strong>Example configuration file</strong></summary>432433```jsonc434{435 "mongoUri": "mongodb://localhost:27017", // Default MongoDB connection string or object of alias-URI pairs436 "connectionOptions": {437 "maxPoolSize": 20, // Maximum number of connections in the pool438 "retryWrites": false, // Whether to retry write operations439 "connectTimeoutMS": 30000, // Connection timeout in milliseconds440 "socketTimeoutMS": 360000, // Socket timeout in milliseconds441 "heartbeatFrequencyMS": 10000, // How often to ping servers for status442 "serverSelectionTimeoutMS": 30000 // Timeout for server selection443 },444 "defaultDbName": "admin", // Default database if not specified in URI445 "connection": {446 "maxRetries": 5, // Maximum number of initial connection attempts447 "maxRetryDelayMs": 30000, // Maximum delay between retries448 "reconnectionRetries": 10, // Maximum reconnection attempts if connection lost449 "initialRetryDelayMs": 1000 // Initial delay between retries450 },451 "disabled": {452 "tools": [], // Array of tools to disable or true to disable all453 "prompts": [], // Array of prompts to disable or true to disable all454 "resources": [] // Array of resources to disable or true to disable all455 },456 "enabled": {457 "tools": true, // Array of tools to enable or true to enable all458 "prompts": true, // Array of prompts to enable or true to enable all459 "resources": true // Array of resources to enable or true to enable all460 },461 "cacheTTL": {462 "stats": 15000, // Stats cache lifetime in milliseconds463 "fields": 30000, // Fields cache lifetime in milliseconds464 "schemas": 60000, // Schema cache lifetime in milliseconds465 "indexes": 120000, // Index cache lifetime in milliseconds466 "collections": 30000, // Collections list cache lifetime in milliseconds467 "serverStatus": 20000 // Server status cache lifetime in milliseconds468 },469 "enabledCaches": [ // List of caches to enable470 "stats", // Statistics cache471 "fields", // Collection fields cache472 "schemas", // Collection schemas cache473 "indexes", // Collection indexes cache474 "collections", // Database collections cache475 "serverStatus" // MongoDB server status cache476 ],477 "memory": {478 "enableGC": true, // Whether to enable garbage collection479 "warningThresholdMB": 1500, // Memory threshold for warnings480 "criticalThresholdMB": 2000 // Memory threshold for cache clearing481 },482 "logLevel": "info", // Log level (info or verbose)483 "disableDestructiveOperationTokens": false, // Whether to skip confirmation for destructive ops484 "watchdogIntervalMs": 30000, // Interval for connection monitoring485 "defaults": {486 "slowMs": 100, // Threshold for slow query detection487 "queryLimit": 10, // Default limit for query results488 "allowDiskUse": true, // Allow operations to use disk for large datasets489 "schemaSampleSize": 100, // Sample size for schema inference490 "aggregationBatchSize": 50 // Batch size for aggregation operations491 },492 "security": {493 "tokenLength": 4, // Length of confirmation tokens494 "tokenExpirationMinutes": 5, // Expiration time for tokens495 "strictDatabaseNameValidation": true // Enforce strict database name validation496 },497 "tools": {498 "transaction": {499 "readConcern": "snapshot", // Read concern level for transactions500 "writeConcern": {501 "w": "majority" // Write concern for transactions502 }503 },504 "bulkOperations": {505 "ordered": true // Whether bulk operations execute in order506 },507 "export": {508 "defaultLimit": -1, // Default limit for exports (-1 = no limit)509 "defaultFormat": "json" // Default export format (json or csv)510 },511 "watchChanges": {512 "maxDurationSeconds": 60, // Maximum duration for change streams513 "defaultDurationSeconds": 10 // Default duration for change streams514 },515 "queryAnalysis": {516 "defaultDurationSeconds": 10 // Default duration for query analysis517 }518 }519}520```521522</details>523524By default, MongoDB Lens looks for the config file at:525526- `~/.mongodb-lens.jsonc` first, then falls back to527- `~/.mongodb-lens.json` if the former doesn't exist528529To customize the config file path, set the environment variable `CONFIG_PATH` to the desired file path.530531Example NPX usage:532533```console534CONFIG_PATH='/path/to/config.json' npx -y mongodb-lens@latest535```536537Example Docker Hub usage:538539```console540docker run --rm -i --network=host --pull=always -v /path/to/config.json:/root/.mongodb-lens.json furey/mongodb-lens541```542543### Configuration: Config File Generation544545You can generate a configuration file automatically using the `config:create` script:546547```console548# NPX Usage (recommended)549npx -y mongodb-lens@latest config:create550551# Node.js Usage552npm run config:create553554# Force overwrite existing files555npx -y mongodb-lens@latest config:create -- --force556npm run config:create -- --force557```558559This script extracts the [example configuration file](#configuration-config-file) above and saves it to: `~/.mongodb-lens.jsonc`560561#### Config File Generation: Custom Path562563You can specify a custom output location using the `CONFIG_PATH` environment variable.564565- If `CONFIG_PATH` has no file extension, it's treated as a directory and `.mongodb-lens.jsonc` is appended566- If `CONFIG_PATH` ends with `.json` (not `.jsonc`) comments are removed from the generated file567568Example NPX usage:569570```console571# With custom path572CONFIG_PATH=/path/to/config.jsonc npx -y mongodb-lens@latest config:create573574# Save to directory (will append .mongodb-lens.jsonc to the path)575CONFIG_PATH=/path/to/directory npx -y mongodb-lens@latest config:create576577# Save as JSON instead of JSONC578CONFIG_PATH=/path/to/config.json npx -y mongodb-lens@latest config:create579```580581Example Node.js usage:582583```console584# With custom path585CONFIG_PATH=/path/to/config.jsonc node mongodb-lens.js config:create586587# Save to directory (will append .mongodb-lens.jsonc to the path)588CONFIG_PATH=/path/to/directory node mongodb-lens.js config:create589590# Save as JSON instead of JSONC591CONFIG_PATH=/path/to/config.json node mongodb-lens.js config:create592```593594### Configuration: Multiple MongoDB Connections595596MongoDB Lens supports multiple MongoDB URIs with aliases in your [config file](#configuration-config-file), allowing you to easily switch between different MongoDB instances using simple names.597598To configure multiple connections, set the `mongoUri` config setting to an object with alias-URI pairs:599600```json601{602 "mongoUri": {603 "main": "mongodb://localhost:27017",604 "backup": "mongodb://localhost:27018",605 "atlas": "mongodb+srv://username:password@cluster.mongodb.net/mydb"606 }607}608```609610With this configuration:611612- The first URI in the list (e.g. `main`) becomes the default connection at startup613- You can switch connections using natural language: `"Connect to backup"` or `"Connect to atlas"`614- The original syntax still works: `"Connect to mongodb://localhost:27018"`615- The `list-connections` tool shows all available connection aliases616617> [!NOTE]<br>618> 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.619620> [!TIP]<br>621> To add connection aliases at runtime, use the `add-connection-alias` tool.622623### Configuration: Environment Variable Overrides624625MongoDB Lens supports environment variable overrides for configuration settings.626627Environment variables take precedence over [config file](#configuration-config-file) settings.628629Config environment variables follow the naming pattern:630631```txt632CONFIG_[SETTING PATH, SNAKE CASED, UPPERCASED]633```634635Example overrides:636637| Config Setting | Environment Variable Override |638| -------------------------------- | ----------------------------------------- |639| `mongoUri` | `CONFIG_MONGO_URI` |640| `logLevel` | `CONFIG_LOG_LEVEL` |641| `defaultDbName` | `CONFIG_DEFAULT_DB_NAME` |642| `defaults.queryLimit` | `CONFIG_DEFAULTS_QUERY_LIMIT` |643| `tools.export.defaultFormat` | `CONFIG_TOOLS_EXPORT_DEFAULT_FORMAT` |644| `connectionOptions.maxPoolSize` | `CONFIG_CONNECTION_OPTIONS_MAX_POOL_SIZE` |645| `connection.reconnectionRetries` | `CONFIG_CONNECTION_RECONNECTION_RETRIES` |646647For environment variable values:648649- For boolean settings, use string values `'true'` or `'false'`.650- For numeric settings, use string representations.651- For nested objects or arrays, use JSON strings.652653Example NPX usage:654655```console656CONFIG_DEFAULTS_QUERY_LIMIT='25' npx -y mongodb-lens@latest657```658659Example Docker Hub usage:660661```console662docker run --rm -i --network=host --pull=always -e CONFIG_DEFAULTS_QUERY_LIMIT='25' furey/mongodb-lens663```664665### Configuration: Cross-Platform Environment Variables666667For consistent environment variable usage across Windows, macOS, and Linux, consider using `cross-env`:6686691. Install cross-env globally:<br>670 ```console671 # Using NPM672 npm install -g cross-env673674 # Using Volta (see: https://volta.sh)675 volta install cross-env676 ```6771. Prefix any NPX or Node.js environment variables in this document's examples:<br>678 ```console679 # Example NPX usage with cross-env680 cross-env CONFIG_DEFAULTS_QUERY_LIMIT='25' npx -y mongodb-lens@latest681682 # Example Node.js usage with cross-env683 cross-env CONFIG_DEFAULTS_QUERY_LIMIT='25' node mongodb-lens.js684 ```685686## Client Setup687688- [Claude Desktop](#client-setup-claude-desktop)689- [MCP Inspector](#client-setup-mcp-inspector)690- [Other MCP Clients](#client-setup-other-mcp-clients)691692### Client Setup: Claude Desktop693694To use MongoDB Lens with Claude Desktop:6956961. Install [Claude Desktop](https://claude.ai/download)6971. Open `claude_desktop_config.json` (create if it doesn't exist):698 - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`699 - Windows: `%APPDATA%\Claude\claude_desktop_config.json`7001. Add the MongoDB Lens server configuration as per [configuration options](#claude-desktop-configuration-options)7011. Restart Claude Desktop7021. Start a conversation with Claude about your MongoDB data703704#### Claude Desktop Configuration Options705706- [Option 1: NPX (Recommended)](#option-1-npx-recommended)707- [Option 2: Docker Hub Image](#option-2-docker-hub-image)708- [Option 3: Local Node.js Installation](#option-3-local-nodejs-installation)709- [Option 4: Local Docker Image](#option-4-local-docker-image)710711For each option:712713- Replace `mongodb://your-connection-string` with your MongoDB connection string or omit it to use the default `mongodb://localhost:27017`.714- To use a custom config file, set [`CONFIG_PATH`](#configuration-config-file) environment variable.715- To include environment variables:716 - For NPX or Node.js add `"env": {}` with key-value pairs, for example:<br>717 ```json718 "command": "/path/to/npx",719 "args": [720 "-y",721 "mongodb-lens@latest",722 "mongodb://your-connection-string"723 ],724 "env": {725 "CONFIG_LOG_LEVEL": "verbose"726 }727 ```728 - For Docker add `-e` flags, for example:<br>729 ```json730 "command": "docker",731 "args": [732 "run", "--rm", "-i",733 "--network=host",734 "--pull=always",735 "-e", "CONFIG_LOG_LEVEL=verbose",736 "furey/mongodb-lens",737 "mongodb://your-connection-string"738 ]739 ```740741##### Option 1: NPX (Recommended)742743```json744{745 "mcpServers": {746 "mongodb-lens": {747 "command": "/path/to/npx",748 "args": [749 "-y",750 "mongodb-lens@latest",751 "mongodb://your-connection-string"752 ]753 }754 }755}756```757758##### Option 2: Docker Hub Image759760```json761{762 "mcpServers": {763 "mongodb-lens": {764 "command": "docker",765 "args": [766 "run", "--rm", "-i",767 "--network=host",768 "--pull=always",769 "furey/mongodb-lens",770 "mongodb://your-connection-string"771 ]772 }773 }774}775```776777##### Option 3: Local Node.js Installation778779```json780{781 "mcpServers": {782 "mongodb-lens": {783 "command": "/path/to/node",784 "args": [785 "/path/to/mongodb-lens.js",786 "mongodb://your-connection-string"787 ]788 }789 }790}791```792793##### Option 4: Local Docker Image794795```json796{797 "mcpServers": {798 "mongodb-lens": {799 "command": "docker",800 "args": [801 "run", "--rm", "-i",802 "--network=host",803 "mongodb-lens",804 "mongodb://your-connection-string"805 ]806 }807 }808}809```810811### Client Setup: MCP Inspector812813[MCP Inspector](https://github.com/modelcontextprotocol/inspector) is a tool designed for testing and debugging MCP servers.814815> [!NOTE]<br>816> MCP Inspector starts a proxy server on port 3000 and web client on port 5173.817818Example NPX usage:8198201. Run MCP Inspector:<br>821 ```console822 # Using default connection string mongodb://localhost:27017823 npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest824825 # Using custom connection string826 npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest mongodb://your-connection-string827828 # Using custom ports829 SERVER_PORT=1234 CLIENT_PORT=5678 npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest830 ```8311. Open MCP Inspector: http://localhost:5173832833MCP Inspector should support the full range of MongoDB Lens capabilities, including autocompletion for collection names and query fields.834835For more, see: [MCP Inspector](https://modelcontextprotocol.io/docs/tools/inspector)836837### Client Setup: Other MCP Clients838839MongoDB Lens should be usable with any MCP-compatible client.840841For more, see: [MCP Documentation: Example Clients](https://modelcontextprotocol.io/clients)842843## Data Protection844845To protect your data while using MongoDB Lens, consider the following:846847- [Read-Only User Accounts](#data-protection-read-only-user-accounts)848- [Working with Database Backups](#data-protection-working-with-database-backups)849- [Data Flow Considerations](#data-protection-data-flow-considerations)850- [Confirmation for Destructive Operations](#data-protection-confirmation-for-destructive-operations)851- [Disabling Destructive Operations](#data-protection-disabling-destructive-operations)852853### Data Protection: Read-Only User Accounts854855When 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.856857To 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:858859```js860use admin861862db.createUser({863 user: 'readonly',864 pwd: 'eXaMpLePaSsWoRd',865 roles: [{ role: 'read', db: 'mydatabase' }]866})867```868869Then, apply those credentials to your MongoDB connection string:870871```txt872mongodb://readonly:eXaMpLePaSsWoRd@localhost:27017/mydatabase873```874875Using 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.876877### Data Protection: Working with Database Backups878879When working with MongoDB Lens, consider connecting to a backup copy of your data hosted on a separate MongoDB instance.880881Start 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`).882883This approach gives you a sandbox to test complex or destructive operations against without risking accidental corruption of your live data.884885### Data Protection: Data Flow Considerations886887- [How Your Data Flows Through the System](#data-flow-considerations-how-your-data-flows-through-the-system)888- [Protecting Sensitive Data with Projection](#data-flow-considerations-protecting-sensitive-data-with-projection)889- [Connection Aliases and Passwords](#data-flow-considerations-connection-aliases-and-passwords)890- [Local Setup for Maximum Safety](#data-flow-considerations-local-setup-for-maximum-safety)891892#### Data Flow Considerations: How Your Data Flows Through the System893894When 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.895896When you send a MongoDB related query through your MCP client, here’s what happens:897898> [!NOTE]<br>899> While this example uses a local MongoDB instance, the same principles apply to remote MongoDB instances.900901```mermaid902sequenceDiagram903 actor User904 box Local Machine #d4f1f9905 participant Client as MCP Client906 participant Lens as MongoDB Lens907 participant MongoDB as MongoDB Instance908 end909 box Remote Server #ffe6cc910 participant LLM as Remote LLM Provider911 end912913 User->>Client: 1. Submit request<br>"Show me all users older than 30"914 Client->>LLM: 2. User request + available tools915 Note over LLM: Interprets request<br>Chooses appropriate tool916 LLM->>Client: 3. Tool selection (find-documents)917 Client->>Lens: 4. Tool run with parameters918 Lens->>MongoDB: 5. Database query919 MongoDB-->>Lens: 6. Database results920 Lens-->>Client: 7. Tool results (formatted data)921 Client->>LLM: 8. Tool results922 Note over LLM: Processes results<br>Formats response923 LLM-->>Client: 9. Processed response924 Client-->>User: 10. Final answer925```9269271. You submit a request<br><sup>➥ e.g. "Show me all users older than 30"</sup>9281. Your client sends the request to the remote LLM<br><sup>➥ The LLM provider receives your exact words along with a list of available MCP tools and their parameters.</sup>9291. The remote LLM interprets your request<br><sup>➥ It determines your intent and instructs the client to use a specific MCP tool with appropriate parameters.</sup>9301. The client asks MongoDB Lens to run the tool<br><sup>➥ This occurs locally on your machine via stdio.</sup>9311. MongoDB Lens queries your MongoDB database9321. MongoDB Lens retrieves your MongoDB query results9331. MongoDB Lens sends the data back to the client<br><sup>➥ The client receives results formatted by MongoDB Lens.</sup>9341. The client forwards the data to the remote LLM<br><sup>➥ The LLM provider sees the exact data returned by MongoDB Lens.</sup>9351. The remote LLM processes the data<br><sup>➥ It may summarize or format the results further.</sup>9361. The remote LLM sends the final response to the client<br><sup>➥ The client displays the answer to you.</sup>937938The 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.939940#### Data Flow Considerations: Protecting Sensitive Data with Projection941942To 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.943944Example projection usage:945946- _"Show me all users older than 30, but use projection to hide their passwords."_<br>947 <sup>➥ Uses `find-documents` tool with projection</sup>948949#### Data Flow Considerations: Connection Aliases and Passwords950951When 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](#configuration-multiple-mongodb-connections), where they remain local and are not transmitted to the LLM.952953#### Data Flow Considerations: Local Setup for Maximum Safety954955While 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.956957### Data Protection: Confirmation for Destructive Operations958959MongoDB 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:9609611. First tool invocation: Returns a 4-digit confirmation token that expires after 5 minutes9621. Second tool invocation: Executes the operation if provided with the valid token963964For an example of the confirmation process, see: [Working with Confirmation Protection](#tutorial-5-working-with-confirmation-protection)965966Tools that require confirmation include:967968- `drop-user`: Remove a database user969- `drop-index`: Remove an index (potential performance impact)970- `drop-database`: Permanently delete a database971- `drop-collection`: Delete a collection and all its documents972- `delete-document`: Delete one or multiple documents973- `bulk-operations`: When including delete operations974- `rename-collection`: When the target collection exists and will be dropped975976This 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.977978> [!NOTE]<br>979> If you're working in a controlled environment where data loss is acceptable, you can configure MongoDB Lens to [bypass confirmation](#bypassing-confirmation-for-destructive-operations) and perform destructive operations immediately.980981#### Bypassing Confirmation for Destructive Operations982983You might want to bypass the token confirmation system.984985Set the environment variable `CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS` to `true` to execute destructive operations immediately without confirmation:986987```console988# Using NPX989CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS=true npx -y mongodb-lens@latest990991# Using Docker992docker run --rm -i --network=host --pull=always -e CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS='true' furey/mongodb-lens993```994995> [!WARNING]<br>996> 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.997998### Data Protection: Disabling Destructive Operations9991000- [Disabling Tools](#disabling-tools)1001- [High-Risk Tools](#high-risk-tools)1002- [Medium-Risk Tools](#medium-risk-tools)1003- [Read-Only Configuration](#read-only-configuration)1004- [Selective Component Enabling](#selective-component-enabling)10051006#### Disabling Tools10071008MongoDB 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](#configuration-config-file):10091010```json1011{1012 "disabled": {1013 "tools": [1014 "drop-user",1015 "drop-index",1016 "drop-database",1017 "drop-collection",1018 "delete-document",1019 "bulk-operations",1020 "rename-collection"1021 ]1022 }1023}1024```10251026> [!NOTE]<br>1027> Resources and prompts can also be disabled via `disabled.resources` and `disabled.prompts` settings.10281029#### High-Risk Tools10301031These tools can cause immediate data loss and should be considered for disabling in sensitive environments:10321033- `drop-user`: Removes database users and their access permissions1034- `drop-index`: Removes indexes (can impact query performance)1035- `drop-database`: Permanently deletes entire databases1036- `drop-collection`: Permanently deletes collections and all their documents1037- `delete-document`: Removes documents matching specified criteria1038- `bulk-operations`: Can perform batch deletions when configured to do so1039- `rename-collection`: Can overwrite existing collections when using the drop target option10401041#### Medium-Risk Tools10421043These tools can modify data but typically don't cause immediate data loss:10441045- `create-user`: Creates users with permissions that could enable further changes1046- `transaction`: Executes multiple operations in a transaction (potential for complex changes)1047- `update-document`: Updates documents which could overwrite existing data10481049#### Read-Only Configuration10501051For a complete read-only configuration, disable all potentially destructive tools:10521053```json1054{1055 "disabled": {1056 "tools": [1057 "drop-user",1058 "drop-index",1059 "create-user",1060 "transaction",1061 "create-index",1062 "drop-database",1063 "drop-collection",1064 "insert-document",1065 "update-document",1066 "delete-document",1067 "bulk-operations",1068 "create-database",1069 "gridfs-operation",1070 "create-collection",1071 "rename-collection",1072 "create-timeseries"1073 ]1074 }1075}1076```10771078This configuration allows MongoDB Lens to query and analyze data while preventing any modifications, providing multiple layers of protection against accidental data loss.10791080#### Selective Component Enabling10811082In addition to [disabling components](#disabling-tools), specify exactly which components should be enabled (implicitly disabling all others) using the `enabled` settings in your [configuration file](#configuration-config-file):10831084```json1085{1086 "enabled": {1087 "tools": [1088 "use-database",1089 "find-documents",1090 "count-documents",1091 "aggregate-data"1092 ]1093 },1094 "disabled": {1095 "resources": true,1096 "prompts": true1097 }1098}1099```11001101> [!IMPORTANT]<br>1102> If a component appears in both `enabled` and `disabled` lists, the `enabled` setting takes precedence.11031104## Tutorial11051106This 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:110711081. [Start Sample Data Container](#tutorial-1-start-sample-data-container)11091. [Import Sample Data](#tutorial-2-import-sample-data)11101. [Connect MongoDB Lens](#tutorial-3-connect-mongodb-lens)11111. [Example Queries](#tutorial-4-example-queries)11121. [Working With Confirmation Protection](#tutorial-5-working-with-confirmation-protection)11131114### Tutorial: 1. Start Sample Data Container11151116> [!NOTE]<br>1117> This tutorial assumes you have [Docker](https://docs.docker.com/get-started/get-docker/) installed and running on your system.11181119> [!IMPORTANT]<br>1120> If Docker is already running a container on port 27017, stop it before proceeding.112111221. Initialise the sample data container:<br>1123 ```console1124 docker run --name mongodb-sampledata -d -p 27017:27017 mongo:61125 ```11261. Verify the container is running without issue:<br>1127 ```console1128 docker ps | grep mongodb-sampledata1129 ```11301131### Tutorial: 2. Import Sample Data11321133MongoDB provides several [sample datasets](https://www.mongodb.com/docs/atlas/sample-data/#available-sample-datasets) which we'll use to explore MongoDB Lens.113411351. Download the sample datasets:1136 ```console<br>1137 curl -LO https://atlas-education.s3.amazonaws.com/sampledata.archive1138 ```11391. Copy the sample datasets into your sample data container:<br>1140 ```console1141 docker cp sampledata.archive mongodb-sampledata:/tmp/1142 ```11431. Import the sample datasets into MongoDB:<br>1144 ```console1145 docker exec -it mongodb-sampledata mongorestore --archive=/tmp/sampledata.archive1146 ```11471148This will import several databases:11491150- `sample_airbnb`: Airbnb listings and reviews1151- `sample_analytics`: Customer and account data1152- `sample_geospatial`: Geographic data1153- `sample_mflix`: Movie data1154- `sample_restaurants`: Restaurant data1155- `sample_supplies`: Supply chain data1156- `sample_training`: Training data for various applications1157- `sample_weatherdata`: Weather measurements11581159### Tutorial: 3. Connect MongoDB Lens11601161[Install](#installation) MongoDB Lens as per the [Quick Start](#quick-start) instructions.11621163Set your [MCP Client](#client-setup) to connect to MongoDB Lens via: `mongodb://localhost:27017`11641165> [!TIP]<br>1166> Omitting the connection string from your MCP Client configuration will default the connection string to `mongodb://localhost:27017`.11671168Example [Claude Desktop configuration](#client-setup-claude-desktop):11691170```json1171{1172 "mcpServers": {1173 "mongodb-lens": {1174 "command": "/path/to/npx",1175 "args": [1176 "-y",1177 "mongodb-lens@latest"1178 ]1179 }1180 }1181}1182```11831184### Tutorial: 4. Example Queries11851186With your MCP Client running and connected to MongoDB Lens, try the following example queries:11871188- [Example Queries: Basic Database Operations](#example-queries-basic-database-operations)1189- [Example Queries: Collection Management](#example-queries-collection-management)1190- [Example Queries: User Management](#example-queries-user-management)1191- [Example Queries: Querying Data](#example-queries-querying-data)1192- [Example Queries: Schema Analysis](#example-queries-schema-analysis)1193- [Example Queries: Data Modification](#example-queries-data-modification)1194- [Example Queries: Performance & Index Management](#example-queries-performance--index-management)1195- [Example Queries: Geospatial & Special Operations](#example-queries-geospatial--special-operations)1196- [Example Queries: Export, Administrative & Other Features](#example-queries-export-administrative--other-features)1197- [Example Queries: Connection Management](#example-queries-connection-management)11981199#### Example Queries: Basic Database Operations12001201- _"List all databases"_<br>1202 <sup>➥ Uses `list-databases` tool</sup>1203- _"What db am I currently using?"_<br>1204 <sup>➥ Uses `current-database` tool</sup>1205- _"Switch to the sample_mflix database"_<br>1206 <sup>➥ Uses `use-database` tool</sup>1207- _"Create a new db called test_db"_<br>1208 <sup>➥ Uses `create-database` tool</sup>1209- _"Create another db called analytics_db and switch to it"_<br>1210 <sup>➥ Uses `create-database` tool with switch=true</sup>1211- _"Drop test_db"_<br>1212 <sup>➥ Uses `drop-database` tool (with confirmation)</sup>12131214#### Example Queries: Collection Management12151216- _"What collections are in the current database?"_<br>1217 <sup>➥ Uses `list-collections` tool</sup>1218- _"Create user_logs collection"_<br>1219 <sup>➥ Uses `create-collection` tool</sup>1220- _"Rename user_logs to system_logs"_<br>1221 <sup>➥ Uses `rename-collection` tool</sup>1222- _"Drop system_logs"_<br>1223 <sup>➥ Uses `drop-collection` tool (with confirmation)</sup>1224- _"Check the data consistency in the movies collection"_<br>1225 <sup>➥ Uses `validate-collection` tool</sup>12261227#### Example Queries: User Management12281229- _"Create a read-only user for analytics"_<br>1230 <sup>➥ Uses `create-user` tool</sup>1231- _"Drop the inactive_user account"_<br>1232 <sup>➥ Uses `drop-user` tool (with confirmation)</sup>12331234#### Example Queries: Querying Data12351236- _"Count all docs in the movies collection"_<br>1237 <sup>➥ Uses `count-documents` tool</sup>1238- _"Find the top 5 movies with the highest IMDB rating"_<br>1239 <sup>➥ Uses `find-documents` tool</sup>1240- _"Show me aggregate data for movies grouped by decade"_<br>1241 <sup>➥ Uses `aggregate-data` tool</sup>1242- _"List all unique countries where movies were produced"_<br>1243 <sup>➥ Uses `distinct-values` tool</sup>1244- _"Search for movies containing godfather in their title"_<br>1245 <sup>➥ Uses `text-search` tool</sup>1246- _"Find German users with last name müller using proper collation"_<br>1247 <sup>➥ Uses `collation-query` tool</sup>12481249#### Example Queries: Schema Analysis12501251- _"What's the schema structure of the movies collection?"_<br>1252 <sup>➥ Uses `analyze-schema` tool</sup>1253- _"Compare users and comments schemas"_<br>1254 <sup>➥ Uses `compare-schemas` tool</sup>1255- _"Generate a schema validator for the movies collection"_<br>1256 <sup>➥ Uses `generate-schema-validator` tool</sup>1257- _"Analyze common query patterns for the movies collection"_<br>1258 <sup>➥ Uses `analyze-query-patterns` tool</sup>12591260#### Example Queries: Data Modification12611262- _"Insert new movie document: \<your field data\>"_<br>1263 <sup>➥ Uses `insert-document` tool</sup>1264- _"Update all movies from 1994 to add a 'classic' flag"_<br>1265 <sup>➥ Uses `update-document` tool</sup>1266- _"Delete all movies with zero ratings"_<br>1267 <sup>➥ Uses `delete-document` tool (with confirmation)</sup>1268- _"Run these bulk operations on the movies collection: \<your JSON data\>"_<br>1269 <sup>➥ Uses `bulk-operations` tool</sup>12701271> [!TIP]<br>1272> 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.12731274#### Example Queries: Performance & Index Management12751276- _"Create an index on the title field in the movies collection"_<br>1277 <sup>➥ Uses `create-index` tool</sup>1278- _"Drop the ratings_idx index"_<br>1279 <sup>➥ Uses `drop-index` tool (with confirmation)</sup>1280- _"Explain the execution plan for finding movies from 1995"_<br>1281 <sup>➥ Uses `explain-query` tool</sup>1282- _"Get statistics for the current db"_<br>1283 <sup>➥ Uses `get-stats` tool with target=database</sup>1284- _"Show collection stats for the movies collection"_<br>1285 <sup>➥ Uses `get-stats` tool with target=collection</sup>12861287#### Example Queries: Geospatial & Special Operations12881289- _"Switch to sample_geospatial db, then find all shipwrecks within 10km of coordinates [-80.12, 26.46]"_<br>1290 <sup>➥ Uses `geo-query` tool</sup>1291- _"Switch to sample_analytics db, then execute a transaction to move funds between accounts: \<account ids\>"_<br>1292 <sup>➥ Uses `transaction` tool</sup>1293- _"Create a time series collection for sensor readings"_<br>1294 <sup>➥ Uses `create-timeseries` tool</sup>1295- _"Watch for changes in the users collection for 30 seconds"_<br>1296 <sup>➥ Uses `watch-changes` tool</sup>1297- _"List all files in the images GridFS bucket"_<br>1298 <sup>➥ Uses `gridfs-operation` tool with operation=list</sup>12991300#### Example Queries: Export, Administrative & Other Features13011302- _"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)"_<br>1303 <sup>➥ Uses `export-data` tool</sup>1304- _"Switch to sample_analytics db, then check its sharding status"_<br>1305 <sup>➥ Uses `shard-status` tool</sup>1306- _"Clear the collections cache"_<br>1307 <sup>➥ Uses `clear-cache` tool with target=collections</sup>1308- _"Clear all caches"_<br>1309 <sup>➥ Uses `clear-cache` tool</sup>1310- _"Switch to sample_weatherdata db then generate an interactive report on its current state"_<br>1311 <sup>➥ Uses numerous tools</sup>13121313#### Example Queries: Connection Management13141315- _"Connect to mongodb://localhost:27018"_<br>1316 <sup>➥ Uses `connect-mongodb` tool</sup>1317- _"Connect to mongodb+srv://username:password@cluster.mongodb.net/mydb"_<br>1318 <sup>➥ Uses `connect-mongodb` tool</sup>1319- _"Connect back to the original mongodb instance"_<br>1320 <sup>➥ Uses `connect-original` tool</sup>1321- _"Connect to replica set without validating the connection: \<replica set details\>"_<br>1322 <sup>➥ Uses `connect-mongodb` tool with validateConnection=false</sup>1323- _"Add connection alias 'prod' for mongodb://username:password@prod-server:27017/mydb"_<br>1324<sup>➥ Uses `add-connection-alias` tool</sup>13251326### Tutorial: 5. Working With Confirmation Protection13271328MongoDB Lens includes a safety mechanism for potentially destructive operations. Here's how it works in practice:132913301. Request to drop a collection:<br>1331 ```1332 "Drop the collection named test_collection"1333 ```13341. MongoDB Lens responds with a warning and confirmation token:<br>1335 ```1336 ⚠️ DESTRUCTIVE OPERATION WARNING ⚠️13371338 You've requested to drop the collection 'test_collection'.13391340 This operation is irreversible and will permanently delete all data in this collection.13411342 To confirm, you must type the 4-digit confirmation code EXACTLY as shown below:13431344 Confirmation code: 987613451346 This code will expire in 5 minutes for security purposes.1347 ```13481. Confirm the operation by submitting the confirmation token:<br>1349 ```1350 "9876"1351 ```13521. MongoDB Lens executes the operation:<br>1353 ```1354 Collection 'test_collection' has been permanently deleted.1355 ```13561357This two-step process prevents accidental data loss by requiring explicit confirmation.13581359> [!NOTE]<br>1360> If you're working in a controlled environment where data loss is acceptable, you can configure MongoDB Lens to [bypass confirmation](#bypassing-confirmation-for-destructive-operations) and perform destructive operations immediately.13611362## Test Suite13631364MongoDB Lens includes a [test suite](./mongodb-lens.test.js) to verify functionality across tools, resources, and prompts.13651366- [Running Tests](#test-suite-running-tests)1367- [Command Line Options](#test-suite-command-line-options)1368- [Examples](#test-suite-examples)13691370### Test Suite: Running Tests13711372The test suite requires a `CONFIG_MONGO_URI` environment variable which can be set to:13731374- a MongoDB connection string (e.g. `mongodb://localhost:27017`)1375- `mongodb-memory-server` (for in-memory testing)13761377```console1378# Run Tests with MongoDB Connection String1379CONFIG_MONGO_URI=mongodb://localhost:27017 node mongodb-lens.test.js13801381# Run Tests with In-Memory MongoDB (requires mongodb-memory-server)1382CONFIG_MONGO_URI=mongodb-memory-server node mongodb-lens.test.js1383```13841385For convenience, the following scripts are available for running tests:13861387```console1388npm test # Fails if no CONFIG_MONGO_URI provided1389npm run test:localhost # Uses mongodb://localhost:270171390npm run test:localhost:verbose # Runs with DEBUG=true for verbose output1391npm run test:in-memory # Uses mongodb-memory-server1392npm run test:in-memory:verbose # Runs with DEBUG=true for verbose output1393```13941395> [!NOTE]<br>1396> The test suite creates temporary databases and collections that are cleaned up after test completion.13971398### Test Suite: Command Line Options13991400| Option | Description |1401| ------------------ | ---------------------------------------------------- |1402| `--list` | List all available tests without running them |1403| `--test=<n>` | Run specific test(s) by name (comma-separated) |1404| `--group=<n>` | Run all tests in specific group(s) (comma-separated) |1405| `--pattern=<glob>` | Run tests matching pattern(s) (comma-separated) |14061407### Test Suite: Examples14081409```console1410# List All Available Tests1411npm test -- --list14121413# Run Only Connection-Related Tests (:27017)1414npm run test:localhost -- --group=Connection\ Tools14151416# Test Specific Database Operations (In-Memory)1417npm run test:in-memory -- --test=create-database\ Tool,drop-database\ Tool14181419# Test All Document-Related Tools (:27017)1420npm run test:localhost -- --pattern=document14211422# Run Resource Tests Only (In-Memory)1423npm run test:in-memory -- --group=Resources14241425# Run Specific Tests Only (In-Memory)1426npm run test:in-memory -- --test=aggregate-data\ Tool,find-documents\ Tool1427```14281429## Disclaimer14301431MongoDB Lens:14321433- is licensed under the [MIT License](./LICENSE).1434- is not affiliated with or endorsed by MongoDB, Inc.1435- is written with the assistance of AI and may contain errors.1436- is intended for educational and experimental purposes only.1437- is provided as-is with no warranty—please use at your own risk.14381439## Support14401441If you've found MongoDB Lens helpful consider supporting my work through:14421443[Buy Me a Coffee](https://www.buymeacoffee.com/furey) | [GitHub Sponsorship](https://github.com/sponsors/furey)14441445Contributions 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.1446
Full transparency — inspect the skill content before installing.