#
tokens: 25403/50000 10/12 files (page 1/3)
lines: on (toggle) GitHub
raw markdown copy reset
This is page 1 of 3. Use http://codebase.md/furey/mongodb-lens?lines=true&page={x} to view the full context.

# Directory Structure

```
├── .dockerhub
│   └── overview.md
├── .dockerignore
├── .github
│   ├── FUNDING.yml
│   └── workflows
│       ├── publish-docker.yml
│       └── publish-npm.yml
├── .gitignore
├── config-create.js
├── Dockerfile
├── LICENSE
├── mongodb-lens.js
├── mongodb-lens.test.js
├── package-lock.json
├── package.json
└── README.md
```

# Files

--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------

```
1 | .DS_Store
2 | node_modules/
3 | repomix*
4 | .mongodb-lens*.json*
5 | 
```

--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------

```
1 | .DS_Store
2 | node_modules/
3 | .dockerhub/
4 | .github/
5 | .git/
6 | .gitignore
7 | repomix*
8 | 
```

--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------

```markdown
   1 | # MongoDB Lens
   2 | 
   3 | [![License](https://img.shields.io/github/license/furey/mongodb-lens)](./LICENSE)
   4 | [![Docker Hub Version](https://img.shields.io/docker/v/furey/mongodb-lens)](https://hub.docker.com/r/furey/mongodb-lens)
   5 | [![NPM Version](https://img.shields.io/npm/v/mongodb-lens)](https://www.npmjs.com/package/mongodb-lens)
   6 | [![Buy Me a Coffee](https://img.shields.io/badge/Buy%20Me%20a%20Coffee-donate-orange.svg)](https://www.buymeacoffee.com/furey)
   7 | 
   8 | **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.
   9 | 
  10 | ## Contents
  11 | 
  12 | - [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)
  22 | 
  23 | ## Quick Start
  24 | 
  25 | - [Install](#installation) MongoDB Lens
  26 | - [Configure](#configuration) MongoDB Lens
  27 | - [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)
  29 | 
  30 | ## Features
  31 | 
  32 | - [Tools](#tools)
  33 | - [Resources](#resources)
  34 | - [Prompts](#prompts)
  35 | - [Other](#other-features)
  36 | 
  37 | ### Tools
  38 | 
  39 | - [`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 alias
  40 | - [`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 pipelines
  41 | - [`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 optimizations
  42 | - [`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 schemas
  43 | - [`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 data
  45 | - [`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 rules
  46 | - [`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 collections
  47 | - [`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 URI
  48 | - [`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 startup
  49 | - [`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 criteria
  50 | - [`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 options
  51 | - [`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 it
  52 | - [`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 optimization
  53 | - [`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 data
  54 | - [`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 roles
  55 | - [`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 context
  56 | - [`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 field
  58 | - [`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 plans
  63 | - [`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 format
  64 | - [`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 sorting
  65 | - [`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 validators
  66 | - [`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 operators
  67 | - [`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 statistics
  68 | - [`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 buckets
  69 | - [`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 collections
  70 | - [`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 database
  71 | - [`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 aliases
  72 | - [`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 databases
  73 | - [`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 collections
  75 | - [`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 fields
  76 | - [`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 transaction
  77 | - [`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 criteria
  78 | - [`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 context
  79 | - [`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 inconsistencies
  80 | - [`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 collections
  81 | 
  82 | ### Resources
  83 | 
  84 | - [`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 collection
  85 | - [`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 collection
  86 | - [`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 collection
  87 | - [`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 collection
  88 | - [`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 database
  89 | - [`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 configuration
  90 | - [`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 database
  91 | - [`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 databases
  92 | - [`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 data
  93 | - [`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 configuration
  94 | - [`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 information
  95 | - [`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 database
  96 | 
  97 | ### Prompts
  98 | 
  99 | - [`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 pipelines
 100 | - [`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 recommendations
 101 | - [`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 cases
 102 | - [`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 recommendations
 103 | - [`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 patterns
 104 | - [`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 plans
 105 | - [`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 explanations
 106 | - [`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 architecture
 107 | - [`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 queries
 108 | - [`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 queries
 109 | - [`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 recommendations
 110 | - [`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 applications
 111 | - [`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 recommendations
 112 | - [`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 pipelines
 113 | 
 114 | ### Other Features
 115 | 
 116 | - [Overview](#other-features-overview)
 117 | - [New Database Metadata](#other-features-new-database-metadata)
 118 | 
 119 | #### Other Features: Overview
 120 | 
 121 | MongoDB Lens includes numerous other features:
 122 | 
 123 | - **[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 operations
 126 | - **[Multiple Connections](#configuration-multiple-mongodb-connections)**: Define and switch between named URI aliases
 127 | - **[Component Disabling](#disabling-tools)**: Selectively disable tools, prompts or resources
 128 | - **Connection Resilience**: Auto-reconnection with exponential backoff
 129 | - **Query Safeguards**: Configurable limits and performance protections
 130 | - **Error Handling**: Comprehensive JSONRPC error codes and messages
 131 | - **Schema Inference**: Efficient schema analysis with intelligent sampling
 132 | - **Credential Protection**: Connection string password obfuscation in logs
 133 | - **Memory Management**: Auto-monitoring and cleanup for large operations
 134 | - **Smart Caching**: Optimized caching for schema, indexes, fields and collections
 135 | - **Backwards Compatible**: Support both modern and legacy MongoDB versions
 136 | 
 137 | #### Other Features: New Database Metadata
 138 | 
 139 | MongoDB Lens inserts a `metadata` collection into each database it creates.
 140 | 
 141 | 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.
 142 | 
 143 | <details>
 144 |   <summary><strong>Example metadata document</strong></summary>
 145 | 
 146 | ```js
 147 | {
 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 | ```
 176 | 
 177 | </details>
 178 | 
 179 | Once you've added your own collections to your new database, you can safely remove the `metadata` collection via the `drop-collection` tool:
 180 | 
 181 | - _"Drop the new database's metadata collection"_<br>
 182 |   <sup>➥ Uses `drop-collection` tool (with confirmation)</sup>
 183 | 
 184 | ## Installation
 185 | 
 186 | MongoDB Lens can be installed and run in several ways:
 187 | 
 188 | - [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)
 194 | 
 195 | ### Installation: NPX
 196 | 
 197 | > [!NOTE]<br>
 198 | > NPX requires [Node.js](https://nodejs.org/en/download) installed and running on your system (suggestion: use [Volta](https://volta.sh)).
 199 | 
 200 | The easiest way to run MongoDB Lens is using NPX.
 201 | 
 202 | First, ensure Node.js is installed:
 203 | 
 204 | ```console
 205 | node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible
 206 | ```
 207 | 
 208 | Then, run MongoDB Lens via NPX:
 209 | 
 210 | ```console
 211 | # Using default connection string mongodb://localhost:27017
 212 | npx -y mongodb-lens
 213 | 
 214 | # Using custom connection string
 215 | npx -y mongodb-lens mongodb://your-connection-string
 216 | 
 217 | # Using "@latest" to keep the package up-to-date
 218 | npx -y mongodb-lens@latest
 219 | ```
 220 | 
 221 | > [!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).
 223 | 
 224 | ### Installation: Docker Hub
 225 | 
 226 | > [!NOTE]<br>
 227 | > Docker Hub requires [Docker](https://docs.docker.com/get-started/get-docker) installed and running on your system.
 228 | 
 229 | First, ensure Docker is installed:
 230 | 
 231 | ```console
 232 | docker --version # Ideally >= v27.x
 233 | ```
 234 | 
 235 | Then, run MongoDB Lens via Docker Hub:
 236 | 
 237 | ```console
 238 | # Using default connection string mongodb://localhost:27017
 239 | docker run --rm -i --network=host furey/mongodb-lens
 240 | 
 241 | # Using custom connection string
 242 | docker run --rm -i --network=host furey/mongodb-lens mongodb://your-connection-string
 243 | 
 244 | # Using "--pull" to keep the Docker image up-to-date
 245 | docker run --rm -i --network=host --pull=always furey/mongodb-lens
 246 | ```
 247 | 
 248 | ### Installation: Node.js from Source
 249 | 
 250 | > [!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)).
 252 | 
 253 | 1. Clone the MongoDB Lens repository:<br>
 254 |     ```console
 255 |     git clone https://github.com/furey/mongodb-lens.git
 256 |     ```
 257 | 1. Navigate to the cloned repository directory:<br>
 258 |     ```console
 259 |     cd /path/to/mongodb-lens
 260 |     ```
 261 | 1. Ensure Node.js is installed:<br>
 262 |     ```console
 263 |     node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible
 264 |     ```
 265 | 1. Install Node.js dependencies:<br>
 266 |     ```console
 267 |     npm ci
 268 |     ```
 269 | 1. Start the server:<br>
 270 |     ```console
 271 |     # Using default connection string mongodb://localhost:27017
 272 |     node mongodb-lens.js
 273 | 
 274 |     # Using custom connection string
 275 |     node mongodb-lens.js mongodb://your-connection-string
 276 |     ```
 277 | 
 278 | ### Installation: Docker from Source
 279 | 
 280 | > [!NOTE]<br>
 281 | > Docker from source requires [Docker](https://docs.docker.com/get-started/get-docker) installed and running on your system.
 282 | 
 283 | 1. Clone the MongoDB Lens repository:<br>
 284 |     ```console
 285 |     git clone https://github.com/furey/mongodb-lens.git
 286 |     ```
 287 | 1. Navigate to the cloned repository directory:<br>
 288 |     ```console
 289 |     cd /path/to/mongodb-lens
 290 |     ```
 291 | 1. Ensure Docker is installed:<br>
 292 |     ```console
 293 |     docker --version # Ideally >= v27.x
 294 |     ```
 295 | 1. Build the Docker image:<br>
 296 |     ```console
 297 |     docker build -t mongodb-lens .
 298 |     ```
 299 | 1. Run the container:<br>
 300 |     ```console
 301 |     # Using default connection string mongodb://localhost:27017
 302 |     docker run --rm -i --network=host mongodb-lens
 303 | 
 304 |     # Using custom connection string
 305 |     docker run --rm -i --network=host mongodb-lens mongodb://your-connection-string
 306 |     ```
 307 | 
 308 | ### Installation Verification
 309 | 
 310 | To verify the installation, paste and run the following JSONRPC message into the server's stdio:
 311 | 
 312 | ```json
 313 | {"method":"resources/read","params":{"uri":"mongodb://databases"},"jsonrpc":"2.0","id":1}
 314 | ```
 315 | 
 316 | The server should respond with a list of databases in your MongoDB instance, for example:
 317 | 
 318 | ```json
 319 | {"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 | ```
 321 | 
 322 | MongoDB Lens is now installed and ready to accept MCP requests.
 323 | 
 324 | ### Installation: Older MongoDB Versions
 325 | 
 326 | 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.
 327 | 
 328 | 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`).
 329 | 
 330 | #### Older MongoDB Versions: Running from Source
 331 | 
 332 | 1. Clone the MongoDB Lens repository:<br>
 333 |     ```console
 334 |     git clone https://github.com/furey/mongodb-lens.git
 335 |     ```
 336 | 1. Navigate to the cloned repository directory:<br>
 337 |     ```console
 338 |     cd /path/to/mongodb-lens
 339 |     ```
 340 | 1. Modify `package.json`:<br>
 341 |     ```diff
 342 |     "dependencies": {
 343 |       ...
 344 |     -  "mongodb": "^6.15.0",  // Or whatever newer version is listed
 345 |     +  "mongodb": "^3.7.4",   // Or whatever 3.x version is compatible with your older MongoDB instance
 346 |       ...
 347 |     }
 348 |     ```
 349 | 1. Install Node.js dependencies:<br>
 350 |     ```console
 351 |     npm install
 352 |     ```
 353 | 1. Start MongoDB Lens:<br>
 354 |     ```console
 355 |     node mongodb-lens.js mongodb://older-mongodb-instance
 356 |     ```
 357 | 
 358 | This will use the older driver version compatible with your MongoDB instance.
 359 | 
 360 | > [!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.
 362 | 
 363 | #### Older MongoDB Versions: Using NPX or Docker
 364 | 
 365 | 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.
 366 | 
 367 | For 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)).
 368 | 
 369 | To run an older version of MongoDB Lens using NPX, specify the version tag:
 370 | 
 371 | ```console
 372 | npx -y [email protected]
 373 | ```
 374 | 
 375 | Similarly for Docker:
 376 | 
 377 | ```console
 378 | docker run --rm -i --network=host furey/mongodb-lens:8.3.0
 379 | ```
 380 | 
 381 | ## Configuration
 382 | 
 383 | - [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)
 389 | 
 390 | ### Configuration: MongoDB Connection String
 391 | 
 392 | The server accepts a MongoDB connection string as its only argument.
 393 | 
 394 | Example NPX usage:
 395 | 
 396 | ```console
 397 | npx -y mongodb-lens@latest mongodb://your-connection-string
 398 | ```
 399 | 
 400 | MongoDB connection strings have the following format:
 401 | 
 402 | ```txt
 403 | mongodb://[username:password@]host[:port][/database][?options]
 404 | ```
 405 | 
 406 | Example connection strings:
 407 | 
 408 | - 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`
 414 | 
 415 | If no connection string is provided, the server will attempt to connect via local connection.
 416 | 
 417 | ### Configuration: Config File
 418 | 
 419 | MongoDB Lens supports extensive customization via JSON configuration file.
 420 | 
 421 | > [!NOTE]<br>
 422 | > The config file is optional. MongoDB Lens will run with default settings if no config file is provided.
 423 | 
 424 | > [!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.
 426 | 
 427 | > [!TIP]<br>
 428 | > MongoDB Lens supports both `.json` and `.jsonc` (JSON with comments) config file formats.
 429 | 
 430 | <details>
 431 |   <summary><strong>Example configuration file</strong></summary>
 432 | 
 433 | ```jsonc
 434 | {
 435 |   "mongoUri": "mongodb://localhost:27017",         // Default MongoDB connection string or object of alias-URI pairs
 436 |   "connectionOptions": {
 437 |     "maxPoolSize": 20,                             // Maximum number of connections in the pool
 438 |     "retryWrites": false,                          // Whether to retry write operations
 439 |     "connectTimeoutMS": 30000,                     // Connection timeout in milliseconds
 440 |     "socketTimeoutMS": 360000,                     // Socket timeout in milliseconds
 441 |     "heartbeatFrequencyMS": 10000,                 // How often to ping servers for status
 442 |     "serverSelectionTimeoutMS": 30000              // Timeout for server selection
 443 |   },
 444 |   "defaultDbName": "admin",                        // Default database if not specified in URI
 445 |   "connection": {
 446 |     "maxRetries": 5,                               // Maximum number of initial connection attempts
 447 |     "maxRetryDelayMs": 30000,                      // Maximum delay between retries
 448 |     "reconnectionRetries": 10,                     // Maximum reconnection attempts if connection lost
 449 |     "initialRetryDelayMs": 1000                    // Initial delay between retries
 450 |   },
 451 |   "disabled": {
 452 |     "tools": [],                                   // Array of tools to disable or true to disable all
 453 |     "prompts": [],                                 // Array of prompts to disable or true to disable all
 454 |     "resources": []                                // Array of resources to disable or true to disable all
 455 |   },
 456 |   "enabled": {
 457 |     "tools": true,                                 // Array of tools to enable or true to enable all
 458 |     "prompts": true,                               // Array of prompts to enable or true to enable all
 459 |     "resources": true                              // Array of resources to enable or true to enable all
 460 |   },
 461 |   "cacheTTL": {
 462 |     "stats": 15000,                                // Stats cache lifetime in milliseconds
 463 |     "fields": 30000,                               // Fields cache lifetime in milliseconds
 464 |     "schemas": 60000,                              // Schema cache lifetime in milliseconds
 465 |     "indexes": 120000,                             // Index cache lifetime in milliseconds
 466 |     "collections": 30000,                          // Collections list cache lifetime in milliseconds
 467 |     "serverStatus": 20000                          // Server status cache lifetime in milliseconds
 468 |   },
 469 |   "enabledCaches": [                               // List of caches to enable
 470 |     "stats",                                       // Statistics cache
 471 |     "fields",                                      // Collection fields cache
 472 |     "schemas",                                     // Collection schemas cache
 473 |     "indexes",                                     // Collection indexes cache
 474 |     "collections",                                 // Database collections cache
 475 |     "serverStatus"                                 // MongoDB server status cache
 476 |   ],
 477 |   "memory": {
 478 |     "enableGC": true,                              // Whether to enable garbage collection
 479 |     "warningThresholdMB": 1500,                    // Memory threshold for warnings
 480 |     "criticalThresholdMB": 2000                    // Memory threshold for cache clearing
 481 |   },
 482 |   "logLevel": "info",                              // Log level (info or verbose)
 483 |   "disableDestructiveOperationTokens": false,      // Whether to skip confirmation for destructive ops
 484 |   "watchdogIntervalMs": 30000,                     // Interval for connection monitoring
 485 |   "defaults": {
 486 |     "slowMs": 100,                                 // Threshold for slow query detection
 487 |     "queryLimit": 10,                              // Default limit for query results
 488 |     "allowDiskUse": true,                          // Allow operations to use disk for large datasets
 489 |     "schemaSampleSize": 100,                       // Sample size for schema inference
 490 |     "aggregationBatchSize": 50                     // Batch size for aggregation operations
 491 |   },
 492 |   "security": {
 493 |     "tokenLength": 4,                              // Length of confirmation tokens
 494 |     "tokenExpirationMinutes": 5,                   // Expiration time for tokens
 495 |     "strictDatabaseNameValidation": true           // Enforce strict database name validation
 496 |   },
 497 |   "tools": {
 498 |     "transaction": {
 499 |       "readConcern": "snapshot",                   // Read concern level for transactions
 500 |       "writeConcern": {
 501 |         "w": "majority"                            // Write concern for transactions
 502 |       }
 503 |     },
 504 |     "bulkOperations": {
 505 |       "ordered": true                              // Whether bulk operations execute in order
 506 |     },
 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 streams
 513 |       "defaultDurationSeconds": 10                 // Default duration for change streams
 514 |     },
 515 |     "queryAnalysis": {
 516 |       "defaultDurationSeconds": 10                 // Default duration for query analysis
 517 |     }
 518 |   }
 519 | }
 520 | ```
 521 | 
 522 | </details>
 523 | 
 524 | By default, MongoDB Lens looks for the config file at:
 525 | 
 526 | - `~/.mongodb-lens.jsonc` first, then falls back to
 527 | - `~/.mongodb-lens.json` if the former doesn't exist
 528 | 
 529 | To customize the config file path, set the environment variable `CONFIG_PATH` to the desired file path.
 530 | 
 531 | Example NPX usage:
 532 | 
 533 | ```console
 534 | CONFIG_PATH='/path/to/config.json' npx -y mongodb-lens@latest
 535 | ```
 536 | 
 537 | Example Docker Hub usage:
 538 | 
 539 | ```console
 540 | docker run --rm -i --network=host --pull=always -v /path/to/config.json:/root/.mongodb-lens.json furey/mongodb-lens
 541 | ```
 542 | 
 543 | ### Configuration: Config File Generation
 544 | 
 545 | You can generate a configuration file automatically using the `config:create` script:
 546 | 
 547 | ```console
 548 | # NPX Usage (recommended)
 549 | npx -y mongodb-lens@latest config:create
 550 | 
 551 | # Node.js Usage
 552 | npm run config:create
 553 | 
 554 | # Force overwrite existing files
 555 | npx -y mongodb-lens@latest config:create -- --force
 556 | npm run config:create -- --force
 557 | ```
 558 | 
 559 | This script extracts the [example configuration file](#configuration-config-file) above and saves it to: `~/.mongodb-lens.jsonc`
 560 | 
 561 | #### Config File Generation: Custom Path
 562 | 
 563 | You can specify a custom output location using the `CONFIG_PATH` environment variable.
 564 | 
 565 | - If `CONFIG_PATH` has no file extension, it's treated as a directory and `.mongodb-lens.jsonc` is appended
 566 | - If `CONFIG_PATH` ends with `.json` (not `.jsonc`) comments are removed from the generated file
 567 | 
 568 | Example NPX usage:
 569 | 
 570 | ```console
 571 | # With custom path
 572 | CONFIG_PATH=/path/to/config.jsonc npx -y mongodb-lens@latest config:create
 573 | 
 574 | # Save to directory (will append .mongodb-lens.jsonc to the path)
 575 | CONFIG_PATH=/path/to/directory npx -y mongodb-lens@latest config:create
 576 | 
 577 | # Save as JSON instead of JSONC
 578 | CONFIG_PATH=/path/to/config.json npx -y mongodb-lens@latest config:create
 579 | ```
 580 | 
 581 | Example Node.js usage:
 582 | 
 583 | ```console
 584 | # With custom path
 585 | CONFIG_PATH=/path/to/config.jsonc node mongodb-lens.js config:create
 586 | 
 587 | # Save to directory (will append .mongodb-lens.jsonc to the path)
 588 | CONFIG_PATH=/path/to/directory node mongodb-lens.js config:create
 589 | 
 590 | # Save as JSON instead of JSONC
 591 | CONFIG_PATH=/path/to/config.json node mongodb-lens.js config:create
 592 | ```
 593 | 
 594 | ### Configuration: Multiple MongoDB Connections
 595 | 
 596 | MongoDB 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.
 597 | 
 598 | To configure multiple connections, set the `mongoUri` config setting to an object with alias-URI pairs:
 599 | 
 600 | ```json
 601 | {
 602 |   "mongoUri": {
 603 |     "main": "mongodb://localhost:27017",
 604 |     "backup": "mongodb://localhost:27018",
 605 |     "atlas": "mongodb+srv://username:[email protected]/mydb"
 606 |   }
 607 | }
 608 | ```
 609 | 
 610 | With this configuration:
 611 | 
 612 | - The first URI in the list (e.g. `main`) becomes the default connection at startup
 613 | - 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 aliases
 616 | 
 617 | > [!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.
 619 | 
 620 | > [!TIP]<br>
 621 | > To add connection aliases at runtime, use the `add-connection-alias` tool.
 622 | 
 623 | ### Configuration: Environment Variable Overrides
 624 | 
 625 | MongoDB Lens supports environment variable overrides for configuration settings.
 626 | 
 627 | Environment variables take precedence over [config file](#configuration-config-file) settings.
 628 | 
 629 | Config environment variables follow the naming pattern:
 630 | 
 631 | ```txt
 632 | CONFIG_[SETTING PATH, SNAKE CASED, UPPERCASED]
 633 | ```
 634 | 
 635 | Example overrides:
 636 | 
 637 | | 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`  |
 646 | 
 647 | For environment variable values:
 648 | 
 649 | - 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.
 652 | 
 653 | Example NPX usage:
 654 | 
 655 | ```console
 656 | CONFIG_DEFAULTS_QUERY_LIMIT='25' npx -y mongodb-lens@latest
 657 | ```
 658 | 
 659 | Example Docker Hub usage:
 660 | 
 661 | ```console
 662 | docker run --rm -i --network=host --pull=always -e CONFIG_DEFAULTS_QUERY_LIMIT='25' furey/mongodb-lens
 663 | ```
 664 | 
 665 | ### Configuration: Cross-Platform Environment Variables
 666 | 
 667 | For consistent environment variable usage across Windows, macOS, and Linux, consider using `cross-env`:
 668 | 
 669 | 1. Install cross-env globally:<br>
 670 |    ```console
 671 |    # Using NPM
 672 |    npm install -g cross-env
 673 | 
 674 |    # Using Volta (see: https://volta.sh)
 675 |    volta install cross-env
 676 |    ```
 677 | 1. Prefix any NPX or Node.js environment variables in this document's examples:<br>
 678 |    ```console
 679 |    # Example NPX usage with cross-env
 680 |    cross-env CONFIG_DEFAULTS_QUERY_LIMIT='25' npx -y mongodb-lens@latest
 681 | 
 682 |    # Example Node.js usage with cross-env
 683 |    cross-env CONFIG_DEFAULTS_QUERY_LIMIT='25' node mongodb-lens.js
 684 |    ```
 685 | 
 686 | ## Client Setup
 687 | 
 688 | - [Claude Desktop](#client-setup-claude-desktop)
 689 | - [MCP Inspector](#client-setup-mcp-inspector)
 690 | - [Other MCP Clients](#client-setup-other-mcp-clients)
 691 | 
 692 | ### Client Setup: Claude Desktop
 693 | 
 694 | To use MongoDB Lens with Claude Desktop:
 695 | 
 696 | 1. Install [Claude Desktop](https://claude.ai/download)
 697 | 1. 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`
 700 | 1. Add the MongoDB Lens server configuration as per [configuration options](#claude-desktop-configuration-options)
 701 | 1. Restart Claude Desktop
 702 | 1. Start a conversation with Claude about your MongoDB data
 703 | 
 704 | #### Claude Desktop Configuration Options
 705 | 
 706 | - [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)
 710 | 
 711 | For each option:
 712 | 
 713 | - 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 |     ```json
 718 |     "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 |     ```json
 730 |     "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 |     ```
 740 | 
 741 | ##### Option 1: NPX (Recommended)
 742 | 
 743 | ```json
 744 | {
 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 | ```
 757 | 
 758 | ##### Option 2: Docker Hub Image
 759 | 
 760 | ```json
 761 | {
 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 | ```
 776 | 
 777 | ##### Option 3: Local Node.js Installation
 778 | 
 779 | ```json
 780 | {
 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 | ```
 792 | 
 793 | ##### Option 4: Local Docker Image
 794 | 
 795 | ```json
 796 | {
 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 | ```
 810 | 
 811 | ### Client Setup: MCP Inspector
 812 | 
 813 | [MCP Inspector](https://github.com/modelcontextprotocol/inspector) is a tool designed for testing and debugging MCP servers.
 814 | 
 815 | > [!NOTE]<br>
 816 | > MCP Inspector starts a proxy server on port 3000 and web client on port 5173.
 817 | 
 818 | Example NPX usage:
 819 | 
 820 | 1. Run MCP Inspector:<br>
 821 |     ```console
 822 |     # Using default connection string mongodb://localhost:27017
 823 |     npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest
 824 | 
 825 |     # Using custom connection string
 826 |     npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest mongodb://your-connection-string
 827 | 
 828 |     # Using custom ports
 829 |     SERVER_PORT=1234 CLIENT_PORT=5678 npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest
 830 |     ```
 831 | 1. Open MCP Inspector: http://localhost:5173
 832 | 
 833 | MCP Inspector should support the full range of MongoDB Lens capabilities, including autocompletion for collection names and query fields.
 834 | 
 835 | For more, see: [MCP Inspector](https://modelcontextprotocol.io/docs/tools/inspector)
 836 | 
 837 | ### Client Setup: Other MCP Clients
 838 | 
 839 | MongoDB Lens should be usable with any MCP-compatible client.
 840 | 
 841 | For more, see: [MCP Documentation: Example Clients](https://modelcontextprotocol.io/clients)
 842 | 
 843 | ## Data Protection
 844 | 
 845 | To protect your data while using MongoDB Lens, consider the following:
 846 | 
 847 | - [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)
 852 | 
 853 | ### Data Protection: Read-Only User Accounts
 854 | 
 855 | When connecting MongoDB Lens to your database, the permissions granted to the user in the MongoDB connection string dictate what actions can be performed. When the use case fits, a read-only user can prevent unintended writes or deletes, ensuring MongoDB Lens can query data but not alter it.
 856 | 
 857 | To set this up, create a user with the `read` role scoped to the database(s) you're targeting. In MongoDB shell, you'd run something like:
 858 | 
 859 | ```js
 860 | use admin
 861 | 
 862 | db.createUser({
 863 |   user: 'readonly',
 864 |   pwd: 'eXaMpLePaSsWoRd',
 865 |   roles: [{ role: 'read', db: 'mydatabase' }]
 866 | })
 867 | ```
 868 | 
 869 | Then, apply those credentials to your MongoDB connection string:
 870 | 
 871 | ```txt
 872 | mongodb://readonly:eXaMpLePaSsWoRd@localhost:27017/mydatabase
 873 | ```
 874 | 
 875 | Using read-only credentials is a simple yet effective way to enforce security boundaries, especially when you're poking around schemas or running ad-hoc queries.
 876 | 
 877 | ### Data Protection: Working with Database Backups
 878 | 
 879 | When working with MongoDB Lens, consider connecting to a backup copy of your data hosted on a separate MongoDB instance.
 880 | 
 881 | Start by generating the backup with `mongodump`. Next, spin up a fresh MongoDB instance (e.g. on a different port like `27018`) and restore the backup there using `mongorestore`. Once it's running, point MongoDB Lens to the backup instance's connection string (e.g. `mongodb://localhost:27018/mydatabase`).
 882 | 
 883 | This approach gives you a sandbox to test complex or destructive operations against without risking accidental corruption of your live data.
 884 | 
 885 | ### Data Protection: Data Flow Considerations
 886 | 
 887 | - [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)
 891 | 
 892 | #### Data Flow Considerations: How Your Data Flows Through the System
 893 | 
 894 | When 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.
 895 | 
 896 | When you send a MongoDB related query through your MCP client, here’s what happens:
 897 | 
 898 | > [!NOTE]<br>
 899 | > While this example uses a local MongoDB instance, the same principles apply to remote MongoDB instances.
 900 | 
 901 | ```mermaid
 902 | sequenceDiagram
 903 |     actor User
 904 |     box Local Machine #d4f1f9
 905 |         participant Client as MCP Client
 906 |         participant Lens as MongoDB Lens
 907 |         participant MongoDB as MongoDB Instance
 908 |     end
 909 |     box Remote Server #ffe6cc
 910 |         participant LLM as Remote LLM Provider
 911 |     end
 912 | 
 913 |     User->>Client: 1. Submit request<br>"Show me all users older than 30"
 914 |     Client->>LLM: 2. User request + available tools
 915 |     Note over LLM: Interprets request<br>Chooses appropriate tool
 916 |     LLM->>Client: 3. Tool selection (find-documents)
 917 |     Client->>Lens: 4. Tool run with parameters
 918 |     Lens->>MongoDB: 5. Database query
 919 |     MongoDB-->>Lens: 6. Database results
 920 |     Lens-->>Client: 7. Tool results (formatted data)
 921 |     Client->>LLM: 8. Tool results
 922 |     Note over LLM: Processes results<br>Formats response
 923 |     LLM-->>Client: 9. Processed response
 924 |     Client-->>User: 10. Final answer
 925 | ```
 926 | 
 927 | 1. You submit a request<br><sup>➥ e.g. "Show me all users older than 30"</sup>
 928 | 1. 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>
 929 | 1. 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>
 930 | 1. The client asks MongoDB Lens to run the tool<br><sup>➥ This occurs locally on your machine via stdio.</sup>
 931 | 1. MongoDB Lens queries your MongoDB database
 932 | 1. MongoDB Lens retrieves your MongoDB query results
 933 | 1. MongoDB Lens sends the data back to the client<br><sup>➥ The client receives results formatted by MongoDB Lens.</sup>
 934 | 1. The client forwards the data to the remote LLM<br><sup>➥ The LLM provider sees the exact data returned by MongoDB Lens.</sup>
 935 | 1. The remote LLM processes the data<br><sup>➥ It may summarize or format the results further.</sup>
 936 | 1. The remote LLM sends the final response to the client<br><sup>➥ The client displays the answer to you.</sup>
 937 | 
 938 | The 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.
 939 | 
 940 | #### Data Flow Considerations: Protecting Sensitive Data with Projection
 941 | 
 942 | To 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.
 943 | 
 944 | Example projection usage:
 945 | 
 946 | - _"Show me all users older than 30, but use projection to hide their passwords."_<br>
 947 |   <sup>➥ Uses `find-documents` tool with projection</sup>
 948 | 
 949 | #### Data Flow Considerations: Connection Aliases and Passwords
 950 | 
 951 | When 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.
 952 | 
 953 | #### Data Flow Considerations: Local Setup for Maximum Safety
 954 | 
 955 | While 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.
 956 | 
 957 | ### Data Protection: Confirmation for Destructive Operations
 958 | 
 959 | MongoDB Lens implements a token-based confirmation system for potentially destructive operations, requiring a two-step process to execute tools that may otherwise result in unchecked data loss:
 960 | 
 961 | 1. First tool invocation: Returns a 4-digit confirmation token that expires after 5 minutes
 962 | 1. Second tool invocation: Executes the operation if provided with the valid token
 963 | 
 964 | For an example of the confirmation process, see: [Working with Confirmation Protection](#tutorial-5-working-with-confirmation-protection)
 965 | 
 966 | Tools that require confirmation include:
 967 | 
 968 | - `drop-user`: Remove a database user
 969 | - `drop-index`: Remove an index (potential performance impact)
 970 | - `drop-database`: Permanently delete a database
 971 | - `drop-collection`: Delete a collection and all its documents
 972 | - `delete-document`: Delete one or multiple documents
 973 | - `bulk-operations`: When including delete operations
 974 | - `rename-collection`: When the target collection exists and will be dropped
 975 | 
 976 | This protection mechanism aims to prevent accidental data loss from typos and unintended commands. It's a safety net ensuring you're aware of the consequences before proceeding with potentially harmful actions.
 977 | 
 978 | > [!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.
 980 | 
 981 | #### Bypassing Confirmation for Destructive Operations
 982 | 
 983 | You might want to bypass the token confirmation system.
 984 | 
 985 | Set the environment variable `CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS` to `true` to execute destructive operations immediately without confirmation:
 986 | 
 987 | ```console
 988 | # Using NPX
 989 | CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS=true npx -y mongodb-lens@latest
 990 | 
 991 | # Using Docker
 992 | docker run --rm -i --network=host --pull=always -e CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS='true' furey/mongodb-lens
 993 | ```
 994 | 
 995 | > [!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.
 997 | 
 998 | ### Data Protection: Disabling Destructive Operations
 999 | 
1000 | - [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)
1005 | 
1006 | #### Disabling Tools
1007 | 
1008 | MongoDB Lens includes several tools that can modify or delete data. To disable specific tools, add them to the `disabled.tools` array in your [configuration file](#configuration-config-file):
1009 | 
1010 | ```json
1011 | {
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 | ```
1025 | 
1026 | > [!NOTE]<br>
1027 | > Resources and prompts can also be disabled via `disabled.resources` and `disabled.prompts` settings.
1028 | 
1029 | #### High-Risk Tools
1030 | 
1031 | These tools can cause immediate data loss and should be considered for disabling in sensitive environments:
1032 | 
1033 | - `drop-user`: Removes database users and their access permissions
1034 | - `drop-index`: Removes indexes (can impact query performance)
1035 | - `drop-database`: Permanently deletes entire databases
1036 | - `drop-collection`: Permanently deletes collections and all their documents
1037 | - `delete-document`: Removes documents matching specified criteria
1038 | - `bulk-operations`: Can perform batch deletions when configured to do so
1039 | - `rename-collection`: Can overwrite existing collections when using the drop target option
1040 | 
1041 | #### Medium-Risk Tools
1042 | 
1043 | These tools can modify data but typically don't cause immediate data loss:
1044 | 
1045 | - `create-user`: Creates users with permissions that could enable further changes
1046 | - `transaction`: Executes multiple operations in a transaction (potential for complex changes)
1047 | - `update-document`: Updates documents which could overwrite existing data
1048 | 
1049 | #### Read-Only Configuration
1050 | 
1051 | For a complete read-only configuration, disable all potentially destructive tools:
1052 | 
1053 | ```json
1054 | {
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 | ```
1077 | 
1078 | This configuration allows MongoDB Lens to query and analyze data while preventing any modifications, providing multiple layers of protection against accidental data loss.
1079 | 
1080 | #### Selective Component Enabling
1081 | 
1082 | In 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):
1083 | 
1084 | ```json
1085 | {
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": true
1097 |   }
1098 | }
1099 | ```
1100 | 
1101 | > [!IMPORTANT]<br>
1102 | > If a component appears in both `enabled` and `disabled` lists, the `enabled` setting takes precedence.
1103 | 
1104 | ## Tutorial
1105 | 
1106 | This following tutorial guides you through setting up a MongoDB container with sample data, then using MongoDB Lens to interact with it through natural language queries:
1107 | 
1108 | 1. [Start Sample Data Container](#tutorial-1-start-sample-data-container)
1109 | 1. [Import Sample Data](#tutorial-2-import-sample-data)
1110 | 1. [Connect MongoDB Lens](#tutorial-3-connect-mongodb-lens)
1111 | 1. [Example Queries](#tutorial-4-example-queries)
1112 | 1. [Working With Confirmation Protection](#tutorial-5-working-with-confirmation-protection)
1113 | 
1114 | ### Tutorial: 1. Start Sample Data Container
1115 | 
1116 | > [!NOTE]<br>
1117 | > This tutorial assumes you have [Docker](https://docs.docker.com/get-started/get-docker/) installed and running on your system.
1118 | 
1119 | > [!IMPORTANT]<br>
1120 | > If Docker is already running a container on port 27017, stop it before proceeding.
1121 | 
1122 | 1. Initialise the sample data container:<br>
1123 |     ```console
1124 |     docker run --name mongodb-sampledata -d -p 27017:27017 mongo:6
1125 |     ```
1126 | 1. Verify the container is running without issue:<br>
1127 |     ```console
1128 |     docker ps | grep mongodb-sampledata
1129 |     ```
1130 | 
1131 | ### Tutorial: 2. Import Sample Data
1132 | 
1133 | MongoDB provides several [sample datasets](https://www.mongodb.com/docs/atlas/sample-data/#available-sample-datasets) which we'll use to explore MongoDB Lens.
1134 | 
1135 | 1. Download the sample datasets:
1136 |     ```console<br>
1137 |     curl -LO https://atlas-education.s3.amazonaws.com/sampledata.archive
1138 |     ```
1139 | 1. Copy the sample datasets into your sample data container:<br>
1140 |     ```console
1141 |     docker cp sampledata.archive mongodb-sampledata:/tmp/
1142 |     ```
1143 | 1. Import the sample datasets into MongoDB:<br>
1144 |     ```console
1145 |     docker exec -it mongodb-sampledata mongorestore --archive=/tmp/sampledata.archive
1146 |     ```
1147 | 
1148 | This will import several databases:
1149 | 
1150 | - `sample_airbnb`: Airbnb listings and reviews
1151 | - `sample_analytics`: Customer and account data
1152 | - `sample_geospatial`: Geographic data
1153 | - `sample_mflix`: Movie data
1154 | - `sample_restaurants`: Restaurant data
1155 | - `sample_supplies`: Supply chain data
1156 | - `sample_training`: Training data for various applications
1157 | - `sample_weatherdata`: Weather measurements
1158 | 
1159 | ### Tutorial: 3. Connect MongoDB Lens
1160 | 
1161 | [Install](#installation) MongoDB Lens as per the [Quick Start](#quick-start) instructions.
1162 | 
1163 | Set your [MCP Client](#client-setup) to connect to MongoDB Lens via: `mongodb://localhost:27017`
1164 | 
1165 | > [!TIP]<br>
1166 | > Omitting the connection string from your MCP Client configuration will default the connection string to `mongodb://localhost:27017`.
1167 | 
1168 | Example [Claude Desktop configuration](#client-setup-claude-desktop):
1169 | 
1170 | ```json
1171 | {
1172 |   "mcpServers": {
1173 |     "mongodb-lens": {
1174 |       "command": "/path/to/npx",
1175 |       "args": [
1176 |         "-y",
1177 |         "mongodb-lens@latest"
1178 |       ]
1179 |     }
1180 |   }
1181 | }
1182 | ```
1183 | 
1184 | ### Tutorial: 4. Example Queries
1185 | 
1186 | With your MCP Client running and connected to MongoDB Lens, try the following example queries:
1187 | 
1188 | - [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)
1198 | 
1199 | #### Example Queries: Basic Database Operations
1200 | 
1201 | - _"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>
1213 | 
1214 | #### Example Queries: Collection Management
1215 | 
1216 | - _"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>
1226 | 
1227 | #### Example Queries: User Management
1228 | 
1229 | - _"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>
1233 | 
1234 | #### Example Queries: Querying Data
1235 | 
1236 | - _"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>
1248 | 
1249 | #### Example Queries: Schema Analysis
1250 | 
1251 | - _"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>
1259 | 
1260 | #### Example Queries: Data Modification
1261 | 
1262 | - _"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>
1270 | 
1271 | > [!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.
1273 | 
1274 | #### Example Queries: Performance & Index Management
1275 | 
1276 | - _"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>
1286 | 
1287 | #### Example Queries: Geospatial & Special Operations
1288 | 
1289 | - _"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>
1299 | 
1300 | #### Example Queries: Export, Administrative & Other Features
1301 | 
1302 | - _"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>
1312 | 
1313 | #### Example Queries: Connection Management
1314 | 
1315 | - _"Connect to mongodb://localhost:27018"_<br>
1316 |   <sup>➥ Uses `connect-mongodb` tool</sup>
1317 | - _"Connect to mongodb+srv://username:[email protected]/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>
1325 | 
1326 | ### Tutorial: 5. Working With Confirmation Protection
1327 | 
1328 | MongoDB Lens includes a safety mechanism for potentially destructive operations. Here's how it works in practice:
1329 | 
1330 | 1. Request to drop a collection:<br>
1331 |     ```
1332 |     "Drop the collection named test_collection"
1333 |     ```
1334 | 1. MongoDB Lens responds with a warning and confirmation token:<br>
1335 |     ```
1336 |     ⚠️ DESTRUCTIVE OPERATION WARNING ⚠️
1337 | 
1338 |     You've requested to drop the collection 'test_collection'.
1339 | 
1340 |     This operation is irreversible and will permanently delete all data in this collection.
1341 | 
1342 |     To confirm, you must type the 4-digit confirmation code EXACTLY as shown below:
1343 | 
1344 |     Confirmation code: 9876
1345 | 
1346 |     This code will expire in 5 minutes for security purposes.
1347 |     ```
1348 | 1. Confirm the operation by submitting the confirmation token:<br>
1349 |     ```
1350 |     "9876"
1351 |     ```
1352 | 1. MongoDB Lens executes the operation:<br>
1353 |     ```
1354 |     Collection 'test_collection' has been permanently deleted.
1355 |     ```
1356 | 
1357 | This two-step process prevents accidental data loss by requiring explicit confirmation.
1358 | 
1359 | > [!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.
1361 | 
1362 | ## Test Suite
1363 | 
1364 | MongoDB Lens includes a [test suite](./mongodb-lens.test.js) to verify functionality across tools, resources, and prompts.
1365 | 
1366 | - [Running Tests](#test-suite-running-tests)
1367 | - [Command Line Options](#test-suite-command-line-options)
1368 | - [Examples](#test-suite-examples)
1369 | 
1370 | ### Test Suite: Running Tests
1371 | 
1372 | The test suite requires a `CONFIG_MONGO_URI` environment variable which can be set to:
1373 | 
1374 | - a MongoDB connection string (e.g. `mongodb://localhost:27017`)
1375 | - `mongodb-memory-server` (for in-memory testing)
1376 | 
1377 | ```console
1378 | # Run Tests with MongoDB Connection String
1379 | CONFIG_MONGO_URI=mongodb://localhost:27017 node mongodb-lens.test.js
1380 | 
1381 | # Run Tests with In-Memory MongoDB (requires mongodb-memory-server)
1382 | CONFIG_MONGO_URI=mongodb-memory-server node mongodb-lens.test.js
1383 | ```
1384 | 
1385 | For convenience, the following scripts are available for running tests:
1386 | 
1387 | ```console
1388 | npm test                        # Fails if no CONFIG_MONGO_URI provided
1389 | npm run test:localhost          # Uses mongodb://localhost:27017
1390 | npm run test:localhost:verbose  # Runs with DEBUG=true for verbose output
1391 | npm run test:in-memory          # Uses mongodb-memory-server
1392 | npm run test:in-memory:verbose  # Runs with DEBUG=true for verbose output
1393 | ```
1394 | 
1395 | > [!NOTE]<br>
1396 | > The test suite creates temporary databases and collections that are cleaned up after test completion.
1397 | 
1398 | ### Test Suite: Command Line Options
1399 | 
1400 | | 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)      |
1406 | 
1407 | ### Test Suite: Examples
1408 | 
1409 | ```console
1410 | # List All Available Tests
1411 | npm test -- --list
1412 | 
1413 | # Run Only Connection-Related Tests (:27017)
1414 | npm run test:localhost -- --group=Connection\ Tools
1415 | 
1416 | # Test Specific Database Operations (In-Memory)
1417 | npm run test:in-memory -- --test=create-database\ Tool,drop-database\ Tool
1418 | 
1419 | # Test All Document-Related Tools (:27017)
1420 | npm run test:localhost -- --pattern=document
1421 | 
1422 | # Run Resource Tests Only (In-Memory)
1423 | npm run test:in-memory -- --group=Resources
1424 | 
1425 | # Run Specific Tests Only (In-Memory)
1426 | npm run test:in-memory -- --test=aggregate-data\ Tool,find-documents\ Tool
1427 | ```
1428 | 
1429 | ## Disclaimer
1430 | 
1431 | MongoDB Lens:
1432 | 
1433 | - 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.
1438 | 
1439 | ## Support
1440 | 
1441 | If you've found MongoDB Lens helpful consider supporting my work through:
1442 | 
1443 | [Buy Me a Coffee](https://www.buymeacoffee.com/furey) | [GitHub Sponsorship](https://github.com/sponsors/furey)
1444 | 
1445 | Contributions help me continue developing and improving this tool, allowing me to dedicate more time to add new features and ensuring it remains a valuable resource for the community.
1446 | 
```

--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------

```yaml
1 | # These are supported funding model platforms
2 | 
3 | github: furey
4 | buy_me_a_coffee: furey
5 | 
```

--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------

```dockerfile
 1 | FROM node:22-alpine
 2 | 
 3 | WORKDIR /app
 4 | 
 5 | COPY package*.json ./
 6 | 
 7 | RUN npm ci --production --no-fund --no-audit
 8 | 
 9 | COPY . .
10 | 
11 | ENTRYPOINT ["node", "mongodb-lens.js"]
12 | 
```

--------------------------------------------------------------------------------
/.github/workflows/publish-npm.yml:
--------------------------------------------------------------------------------

```yaml
 1 | name: Publish to NPM
 2 | 
 3 | on:
 4 |   release:
 5 |     types: [created]
 6 | 
 7 | jobs:
 8 |   build:
 9 |     runs-on: ubuntu-latest
10 |     steps:
11 |       - uses: actions/checkout@v4
12 |       - uses: actions/setup-node@v4
13 |         with:
14 |           node-version: 22
15 |           registry-url: https://registry.npmjs.org/
16 |       - run: npm ci
17 |       - run: npm publish
18 |         env:
19 |           NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
20 | 
```

--------------------------------------------------------------------------------
/.github/workflows/publish-docker.yml:
--------------------------------------------------------------------------------

```yaml
 1 | name: Publish to Docker Hub
 2 | 
 3 | on:
 4 |   release:
 5 |     types: [created]
 6 | 
 7 | jobs:
 8 |   docker:
 9 |     runs-on: ubuntu-latest
10 |     steps:
11 |       - name: Checkout
12 |         uses: actions/checkout@v4
13 |       
14 |       - name: Set up QEMU
15 |         uses: docker/setup-qemu-action@v3
16 |       
17 |       - name: Set up Docker Buildx
18 |         uses: docker/setup-buildx-action@v3
19 |       
20 |       - name: Login to Docker Hub
21 |         uses: docker/login-action@v3
22 |         with:
23 |           username: ${{ vars.DOCKERHUB_USERNAME }}
24 |           password: ${{ secrets.DOCKERHUB_TOKEN }}
25 |       
26 |       - name: Extract metadata
27 |         id: meta
28 |         uses: docker/metadata-action@v5
29 |         with:
30 |           images: furey/mongodb-lens
31 |           tags: |
32 |             type=semver,pattern={{version}}
33 |             type=semver,pattern={{major}}.{{minor}}
34 |             latest
35 | 
36 |       - name: Build and push
37 |         uses: docker/build-push-action@v5
38 |         with:
39 |           context: .
40 |           platforms: linux/amd64,linux/arm64
41 |           push: true
42 |           tags: ${{ steps.meta.outputs.tags }}
43 |           labels: ${{ steps.meta.outputs.labels }}
44 | 
```

--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------

```json
 1 | {
 2 |   "name": "mongodb-lens",
 3 |   "version": "9.1.4",
 4 |   "author": "James Furey (https://about.me/jamesfurey)",
 5 |   "description": "MongoDB Lens: Full Featured MCP Server for MongoDB Databases",
 6 |   "license": "MIT",
 7 |   "type": "module",
 8 |   "main": "mongodb-lens.js",
 9 |   "bin": {
10 |     "mongodb-lens": "mongodb-lens.js"
11 |   },
12 |   "files": [
13 |     "mongodb-lens.js",
14 |     "config-create.js",
15 |     "package.json",
16 |     "README.md",
17 |     "LICENSE"
18 |   ],
19 |   "scripts": {
20 |     "start": "node mongodb-lens.js",
21 |     "start:gc": "node --expose-gc mongodb-lens.js",
22 |     "start:debug": "node --inspect mongodb-lens.js",
23 |     "start:verbose": "cross-env CONFIG_LOG_LEVEL=verbose node mongodb-lens.js",
24 |     "start:inspector": "npx -y @modelcontextprotocol/inspector node mongodb-lens",
25 |     "docker:hub:run": "docker run --rm -i --network=host --pull always furey/mongodb-lens",
26 |     "docker:local:build": "docker build -t mongodb-lens .",
27 |     "docker:local:run": "docker run --rm -i --network=host mongodb-lens",
28 |     "config:create": "node config-create.js",
29 |     "test": "node mongodb-lens.test.js",
30 |     "test:localhost": "cross-env CONFIG_MONGO_URI=mongodb://localhost:27017 node mongodb-lens.test.js",
31 |     "test:localhost:verbose": "cross-env DEBUG=true CONFIG_MONGO_URI=mongodb://localhost:27017 node mongodb-lens.test.js",
32 |     "test:in-memory": "cross-env CONFIG_MONGO_URI=mongodb-memory-server node mongodb-lens.test.js",
33 |     "test:in-memory:verbose": "cross-env DEBUG=true CONFIG_MONGO_URI=mongodb-memory-server node mongodb-lens.test.js"
34 |   },
35 |   "keywords": [
36 |     "ai",
37 |     "llm",
38 |     "mcp",
39 |     "claude",
40 |     "mongodb",
41 |     "database",
42 |     "model-context-protocol"
43 |   ],
44 |   "dependencies": {
45 |     "@modelcontextprotocol/sdk": "^1.8.0",
46 |     "cross-env": "^7.0.3",
47 |     "lodash": "^4.17.21",
48 |     "mongodb": "^6.15.0",
49 |     "strip-json-comments": "^5.0.1",
50 |     "zod": "^3.24.2"
51 |   },
52 |   "devDependencies": {
53 |     "mongodb-memory-server": "^10.1.4"
54 |   },
55 |   "volta": {
56 |     "node": "22.14.0"
57 |   },
58 |   "repository": {
59 |     "type": "git",
60 |     "url": "git+https://github.com/furey/mongodb-lens.git"
61 |   },
62 |   "engines": {
63 |     "node": ">=18.0.0"
64 |   }
65 | }
66 | 
```

--------------------------------------------------------------------------------
/.dockerhub/overview.md:
--------------------------------------------------------------------------------

```markdown
 1 | # MongoDB Lens
 2 | 
 3 | [![Docker Pulls](https://img.shields.io/docker/pulls/furey/mongodb-lens)](https://hub.docker.com/r/furey/mongodb-lens)<br>
 4 | [![Docker Image Size (latest by date)](https://img.shields.io/docker/image-size/furey/mongodb-lens)](https://hub.docker.com/r/furey/mongodb-lens)<br>
 5 | [![Buy Me a Coffee](https://img.shields.io/badge/Buy%20Me%20a%20Coffee-donate-orange.svg)](https://www.buymeacoffee.com/furey)
 6 | 
 7 | - [Overview](#overview)
 8 | - [Features](#features)
 9 | - [Usage](#usage)
10 | - [Links](#links)
11 | - [Disclaimer](#disclaimer)
12 | - [Support](#support)
13 | 
14 | ## Overview
15 | 
16 | <strong>MongoDB Lens</strong> is a Model Context Protocol (MCP) server providing full-featured MongoDB database access to LLMs like Claude. It enables natural language interaction with MongoDB databases for querying, aggregation, performance optimization, schema analysis, and more.
17 | 
18 | ## Features
19 | 
20 | See: [GitHub Documentation → Features](https://github.com/furey/mongodb-lens?tab=readme-ov-file#features)
21 | 
22 | ## Usage
23 | 
24 | ```bash
25 | # Basic usage with local MongoDB
26 | docker run --rm -i --network=host furey/mongodb-lens
27 | 
28 | # With custom connection string
29 | docker run --rm -i --network=host furey/mongodb-lens mongodb://username:password@hostname:27017/database
30 | 
31 | # With verbose logging
32 | docker run --rm -i --network=host -e CONFIG_LOG_LEVEL='verbose' furey/mongodb-lens
33 | ```
34 | 
35 | ## Links
36 | 
37 | - [NPM Package](https://www.npmjs.com/package/mongodb-lens)
38 | - [GitHub Repository](https://github.com/furey/mongodb-lens)
39 | - [GitHub Documentation](https://github.com/furey/mongodb-lens/blob/main/README.md)
40 | 
41 | ## Disclaimer
42 | 
43 | MongoDB Lens:
44 | 
45 | - is licensed under the [MIT License](./LICENSE).
46 | - is not affiliated with or endorsed by MongoDB, Inc.
47 | - is written with the assistance of AI and may contain errors.
48 | - is intended for educational and experimental purposes only.
49 | - is provided as-is with no warranty or support—use at your own risk.
50 | 
51 | ## Support
52 | 
53 | If you've found MongoDB Lens helpful consider supporting my work through:
54 | 
55 | [Buy Me a Coffee](https://www.buymeacoffee.com/furey) | [GitHub Sponsorship](https://github.com/sponsors/furey)
56 | 
57 | Contributions help me continue developing and improving this tool, allowing me to dedicate more time to add new features and ensuring it remains a valuable resource for the community.
58 | 
```

--------------------------------------------------------------------------------
/config-create.js:
--------------------------------------------------------------------------------

```javascript
 1 | #!/usr/bin/env node
 2 | 
 3 | import { join, dirname, extname, resolve } from 'path'
 4 | import stripJsonComments from 'strip-json-comments'
 5 | import { readFile, writeFile } from 'fs/promises'
 6 | import { fileURLToPath } from 'url'
 7 | import { existsSync } from 'fs'
 8 | 
 9 | const __filename = fileURLToPath(import.meta.url)
10 | const __dirname = dirname(__filename)
11 | 
12 | const run = async () => {
13 |   const homeDir = process.env.HOME || process.env.USERPROFILE
14 | 
15 |   let configPath = process.env.CONFIG_PATH || join(homeDir, '.mongodb-lens.jsonc')
16 | 
17 |   if (!extname(configPath)) configPath = join(configPath, '.mongodb-lens.jsonc')
18 | 
19 |   if (!configPath.endsWith('.json') && !configPath.endsWith('.jsonc')) {
20 |     console.error('Error: Configuration file must have .json or .jsonc extension')
21 |     process.exit(1)
22 |   }
23 | 
24 |   configPath = resolve(configPath)
25 | 
26 |   try {
27 |     const configContent = await extractConfigFromReadme()
28 | 
29 |     if (existsSync(configPath)) {
30 |       const overwrite = process.argv.includes('--force')
31 |       if (!overwrite) {
32 |         console.log(`Configuration file already exists at: ${configPath}`)
33 |         console.log('Use --force to overwrite it.')
34 |         return
35 |       }
36 |       console.log(`Overwriting existing configuration file at: ${configPath}`)
37 |     }
38 | 
39 |     let finalContent = configContent
40 |     if (configPath.endsWith('.json')) finalContent = stripJsonComments(configContent)
41 | 
42 |     finalContent = finalContent
43 |       .split('\n')
44 |       .map(line => line.trimEnd())
45 |       .join('\n')
46 | 
47 |     await writeFile(configPath, finalContent, 'utf8')
48 |     console.log(`Configuration file created successfully at: ${configPath}`)
49 |   } catch (error) {
50 |     console.error('Error creating configuration file:', error.message)
51 |     process.exit(1)
52 |   }
53 | }
54 | 
55 | const extractConfigFromReadme = async () => {
56 |   try {
57 |     const possiblePaths = [
58 |       join(__dirname, 'README.md'),
59 |       join(__dirname, '..', 'README.md'),
60 |       join(process.cwd(), 'README.md')
61 |     ]
62 | 
63 |     let readmeContent = null
64 | 
65 |     for (const path of possiblePaths) {
66 |       if (existsSync(path)) {
67 |         readmeContent = await readFile(path, 'utf8')
68 |         console.log(`Found README at: ${path}`)
69 |         break
70 |       }
71 |     }
72 | 
73 |     if (!readmeContent) throw new Error('README.md not found in expected locations')
74 | 
75 |     const configRegex = /Example configuration file[\s\S]*?```jsonc\s*([\s\S]*?)```/
76 |     const match = readmeContent.match(configRegex)
77 | 
78 |     if (!match || !match[1]) throw new Error('Could not find example configuration in README.md')
79 | 
80 |     return match[1].trim()
81 |   } catch (error) {
82 |     console.error('Error extracting configuration from README:', error.message)
83 |     throw error
84 |   }
85 | }
86 | 
87 | run()
88 | 
```
Page 1/3FirstPrevNextLast