Skip to content
Back to search

mongodb-lens

🍃🔎 MongoDB Lens: Full Featured MCP Server for MongoDB Databases

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/furey/mongodb-lens with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/furey/mongodb-lens'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/furey--mongodb-lens/badge.svg)](/listings/furey--mongodb-lens)

HTML

<a href="/listings/furey--mongodb-lens"><img src="/api/listings/furey--mongodb-lens/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

MongoDB Lens can be installed and run in several ways:

- [NPX](#installation-npx) (Easiest) - [Docker Hub](#installation-docker-hub) - [Node.js from Source](#installation-nodejs-from-source) - [Docker from Source](#installation-docker-from-source) - [Installation Verification](#installation-verification) - [Older MongoDB Versions](#installation-older-mongodb-versions)

Installation: NPX

> [!NOTE]<br> > NPX requires [Node.js](https://nodejs.org/en/download) installed and running on your system (suggestion: use [Volta](https://volta.sh)).

The easiest way to run MongoDB Lens is using NPX.

First, ensure Node.js is installed:

node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible

Then, run MongoDB Lens via NPX:

# Using default connection string mongodb://localhost:27017
npx -y mongodb-lens

# Using custom connection string
npx -y mongodb-lens mongodb://your-connection-string

# Using "@latest" to keep the package up-to-date
npx -y mongodb-lens@latest

> [!TIP]<br> > 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).

Installation: Docker Hub

> [!NOTE]<br> > Docker Hub requires [Docker](https://docs.docker.com/get-started/get-docker) installed and running on your system.

First, ensure Docker is installed:

docker --version # Ideally >= v27.x

Then, run MongoDB Lens via Docker Hub:

# Using default connection string mongodb://localhost:27017
docker run --rm -i --network=host furey/mongodb-lens

# Using custom connection string
docker run --rm -i --network=host furey/mongodb-lens mongodb://your-connection-string

# Using "--pull" to keep the Docker image up-to-date
docker run --rm -i --network=host --pull=always furey/mongodb-lens

Installation: Node.js from Source

> [!NOTE]<br> > Node.js from source requires [Node.js](https://nodejs.org/en/download) installed and running on your system (suggestion: use [Volta](https://volta.sh)).

1. Clone the MongoDB Lens repository:<br> ```console git clone https://github.com/furey/mongodb-lens.git ``` 1. Navigate to the cloned repository directory:<br> ```console cd /path/to/mongodb-lens ``` 1. Ensure Node.js is installed:<br> ```console node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible ``` 1. Install Node.js dependencies:<br> ```console npm ci ``` 1. Start the server:<br> ```console # Using default connection string mongodb://localhost:27017 node mongodb-lens.js

# Using custom connection string node mongodb-lens.js mongodb://your-connection-string ```

Installation: Docker from Source

> [!NOTE]<br> > Docker from source requires [Docker](https://docs.docker.com/get-started/get-docker) installed and running on your system.

1. Clone the MongoDB Lens repository:<br> ```console git clone https://github.com/furey/mongodb-lens.git ``` 1. Navigate to the cloned repository directory:<br> ```console cd /path/to/mongodb-lens ``` 1. Ensure Docker is installed:<br> ```console docker --version # Ideally >= v27.x ``` 1. Build the Docker image:<br> ```console docker build -t mongodb-lens . ``` 1. Run the container:<br> ```console # Using default connection string mongodb://localhost:27017 docker run --rm -i --network=host mongodb-lens

# Using custom connection string docker run --rm -i --network=host mongodb-lens mongodb://your-connection-string ```

Installation Verification

To verify the installation, paste and run the following JSONRPC message into the server's stdio:

{"method":"resources/read","params":{"uri":"mongodb://databases"},"jsonrpc":"2.0","id":1}

The server should respond with a list of databases in your MongoDB instance, for example:

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,445 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # MongoDB Lens
  2. [![License](https://img.shields.io/github/license/furey/mongodb-lens)](./LICENSE)
  3. [![Docker Hub Version](https://img.shields.io/docker/v/furey/mongodb-lens)](https://hub.docker.com/r/furey/mongodb-lens)
  4. [![NPM Version](https://img.shields.io/npm/v/mongodb-lens)](https://www.npmjs.com/package/mongodb-lens)
  5. [![Buy Me a Coffee](https://img.shields.io/badge/Buy%20Me%20a%20Coffee-donate-orange.svg)](https://www.buymeacoffee.com/furey)
  6. **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.
  7. ## Contents
  8. - [Quick Start](#quick-start)
  9. - [Features](#features)
  10. - [Installation](#installation)
  11. - [Configuration](#configuration)
  12. - [Client Setup](#client-setup)
  13. - [Data Protection](#data-protection)
  14. - [Tutorial](#tutorial)
  15. - [Test Suite](#test-suite)
  16. - [Disclaimer](#disclaimer)
  17. - [Support](#support)
  18. ## Quick Start
  19. - [Install](#installation) MongoDB Lens
  20. - [Configure](#configuration) MongoDB Lens
  21. - [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)
  22. - Explore your MongoDB databases with [natural language queries](#tutorial-4-example-queries)
  23. ## Features
  24. - [Tools](#tools)
  25. - [Resources](#resources)
  26. - [Prompts](#prompts)
  27. - [Other](#other-features)
  28. ### Tools
  29. - [`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
  30. - [`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
  31. - [`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
  32. - [`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
  33. - [`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)
  34. - [`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
  35. - [`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
  36. - [`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
  37. - [`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
  38. - [`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
  39. - [`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
  40. - [`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
  41. - [`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
  42. - [`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
  43. - [`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
  44. - [`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
  45. - [`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
  46. - [`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))
  47. - [`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
  48. - [`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))
  49. - [`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))
  50. - [`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))
  51. - [`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))
  52. - [`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
  53. - [`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
  54. - [`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
  55. - [`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
  56. - [`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
  57. - [`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
  58. - [`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
  59. - [`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
  60. - [`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
  61. - [`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
  62. - [`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
  63. - [`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)
  64. - [`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
  65. - [`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
  66. - [`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
  67. - [`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
  68. - [`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
  69. - [`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
  70. - [`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
  71. ### Resources
  72. - [`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
  73. - [`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
  74. - [`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
  75. - [`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
  76. - [`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
  77. - [`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
  78. - [`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
  79. - [`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
  80. - [`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
  81. - [`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
  82. - [`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
  83. - [`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
  84. ### Prompts
  85. - [`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
  86. - [`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
  87. - [`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
  88. - [`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
  89. - [`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
  90. - [`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
  91. - [`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
  92. - [`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
  93. - [`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
  94. - [`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
  95. - [`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
  96. - [`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
  97. - [`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
  98. - [`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
  99. ### Other Features
  100. - [Overview](#other-features-overview)
  101. - [New Database Metadata](#other-features-new-database-metadata)
  102. #### Other Features: Overview
  103. MongoDB Lens includes numerous other features:
  104. - **[Config File](#configuration-config-file)**: Custom configuration via `~/.mongodb-lens.[jsonc|json]`
  105. - **[Env Var Overrides](#configuration-environment-variable-overrides)**: Override config settings via `process.env.CONFIG_*`
  106. - **[Confirmation System](#data-protection-confirmation-for-destructive-operations)**: Two-step verification for destructive operations
  107. - **[Multiple Connections](#configuration-multiple-mongodb-connections)**: Define and switch between named URI aliases
  108. - **[Component Disabling](#disabling-tools)**: Selectively disable tools, prompts or resources
  109. - **Connection Resilience**: Auto-reconnection with exponential backoff
  110. - **Query Safeguards**: Configurable limits and performance protections
  111. - **Error Handling**: Comprehensive JSONRPC error codes and messages
  112. - **Schema Inference**: Efficient schema analysis with intelligent sampling
  113. - **Credential Protection**: Connection string password obfuscation in logs
  114. - **Memory Management**: Auto-monitoring and cleanup for large operations
  115. - **Smart Caching**: Optimized caching for schema, indexes, fields and collections
  116. - **Backwards Compatible**: Support both modern and legacy MongoDB versions
  117. #### Other Features: New Database Metadata
  118. MongoDB Lens inserts a `metadata` collection into each database it creates.
  119. 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.
  120. <details>
  121. <summary><strong>Example metadata document</strong></summary>
  122. ```js
  123. {
  124. "_id" : ObjectId("67d5284463788ec38aecee14"),
  125. "created" : {
  126. "timestamp" : ISODate("2025-03-15T07:12:04.705Z"),
  127. "tool" : "MongoDB Lens v5.0.7",
  128. "user" : "anonymous"
  129. },
  130. "mongodb" : {
  131. "version" : "3.6.23",
  132. "connectionInfo" : {
  133. "host" : "unknown",
  134. "readPreference" : "primary"
  135. }
  136. },
  137. "database" : {
  138. "name" : "example_database",
  139. "description" : "Created via MongoDB Lens"
  140. },
  141. "system" : {
  142. "hostname" : "unknown",
  143. "platform" : "darwin",
  144. "nodeVersion" : "v22.14.0"
  145. },
  146. "lens" : {
  147. "version" : "5.0.7",
  148. "startTimestamp" : ISODate("2025-03-15T07:10:06.084Z")
  149. }
  150. }
  151. ```
  152. </details>
  153. Once you've added your own collections to your new database, you can safely remove the `metadata` collection via the `drop-collection` tool:
  154. - _"Drop the new database's metadata collection"_<br>
  155. <sup>➥ Uses `drop-collection` tool (with confirmation)</sup>
  156. ## Installation
  157. MongoDB Lens can be installed and run in several ways:
  158. - [NPX](#installation-npx) (Easiest)
  159. - [Docker Hub](#installation-docker-hub)
  160. - [Node.js from Source](#installation-nodejs-from-source)
  161. - [Docker from Source](#installation-docker-from-source)
  162. - [Installation Verification](#installation-verification)
  163. - [Older MongoDB Versions](#installation-older-mongodb-versions)
  164. ### Installation: NPX
  165. > [!NOTE]<br>
  166. > NPX requires [Node.js](https://nodejs.org/en/download) installed and running on your system (suggestion: use [Volta](https://volta.sh)).
  167. The easiest way to run MongoDB Lens is using NPX.
  168. First, ensure Node.js is installed:
  169. ```console
  170. node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible
  171. ```
  172. Then, run MongoDB Lens via NPX:
  173. ```console
  174. # Using default connection string mongodb://localhost:27017
  175. npx -y mongodb-lens
  176. # Using custom connection string
  177. npx -y mongodb-lens mongodb://your-connection-string
  178. # Using "@latest" to keep the package up-to-date
  179. npx -y mongodb-lens@latest
  180. ```
  181. > [!TIP]<br>
  182. > 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).
  183. ### Installation: Docker Hub
  184. > [!NOTE]<br>
  185. > Docker Hub requires [Docker](https://docs.docker.com/get-started/get-docker) installed and running on your system.
  186. First, ensure Docker is installed:
  187. ```console
  188. docker --version # Ideally >= v27.x
  189. ```
  190. Then, run MongoDB Lens via Docker Hub:
  191. ```console
  192. # Using default connection string mongodb://localhost:27017
  193. docker run --rm -i --network=host furey/mongodb-lens
  194. # Using custom connection string
  195. docker run --rm -i --network=host furey/mongodb-lens mongodb://your-connection-string
  196. # Using "--pull" to keep the Docker image up-to-date
  197. docker run --rm -i --network=host --pull=always furey/mongodb-lens
  198. ```
  199. ### Installation: Node.js from Source
  200. > [!NOTE]<br>
  201. > Node.js from source requires [Node.js](https://nodejs.org/en/download) installed and running on your system (suggestion: use [Volta](https://volta.sh)).
  202. 1. Clone the MongoDB Lens repository:<br>
  203. ```console
  204. git clone https://github.com/furey/mongodb-lens.git
  205. ```
  206. 1. Navigate to the cloned repository directory:<br>
  207. ```console
  208. cd /path/to/mongodb-lens
  209. ```
  210. 1. Ensure Node.js is installed:<br>
  211. ```console
  212. node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible
  213. ```
  214. 1. Install Node.js dependencies:<br>
  215. ```console
  216. npm ci
  217. ```
  218. 1. Start the server:<br>
  219. ```console
  220. # Using default connection string mongodb://localhost:27017
  221. node mongodb-lens.js
  222. # Using custom connection string
  223. node mongodb-lens.js mongodb://your-connection-string
  224. ```
  225. ### Installation: Docker from Source
  226. > [!NOTE]<br>
  227. > Docker from source requires [Docker](https://docs.docker.com/get-started/get-docker) installed and running on your system.
  228. 1. Clone the MongoDB Lens repository:<br>
  229. ```console
  230. git clone https://github.com/furey/mongodb-lens.git
  231. ```
  232. 1. Navigate to the cloned repository directory:<br>
  233. ```console
  234. cd /path/to/mongodb-lens
  235. ```
  236. 1. Ensure Docker is installed:<br>
  237. ```console
  238. docker --version # Ideally >= v27.x
  239. ```
  240. 1. Build the Docker image:<br>
  241. ```console
  242. docker build -t mongodb-lens .
  243. ```
  244. 1. Run the container:<br>
  245. ```console
  246. # Using default connection string mongodb://localhost:27017
  247. docker run --rm -i --network=host mongodb-lens
  248. # Using custom connection string
  249. docker run --rm -i --network=host mongodb-lens mongodb://your-connection-string
  250. ```
  251. ### Installation Verification
  252. To verify the installation, paste and run the following JSONRPC message into the server's stdio:
  253. ```json
  254. {"method":"resources/read","params":{"uri":"mongodb://databases"},"jsonrpc":"2.0","id":1}
  255. ```
  256. The server should respond with a list of databases in your MongoDB instance, for example:
  257. ```json
  258. {"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}
  259. ```
  260. MongoDB Lens is now installed and ready to accept MCP requests.
  261. ### Installation: Older MongoDB Versions
  262. 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.
  263. 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`).
  264. #### Older MongoDB Versions: Running from Source
  265. 1. Clone the MongoDB Lens repository:<br>
  266. ```console
  267. git clone https://github.com/furey/mongodb-lens.git
  268. ```
  269. 1. Navigate to the cloned repository directory:<br>
  270. ```console
  271. cd /path/to/mongodb-lens
  272. ```
  273. 1. Modify `package.json`:<br>
  274. ```diff
  275. "dependencies": {
  276. ...
  277. - "mongodb": "^6.15.0", // Or whatever newer version is listed
  278. + "mongodb": "^3.7.4", // Or whatever 3.x version is compatible with your older MongoDB instance
  279. ...
  280. }
  281. ```
  282. 1. Install Node.js dependencies:<br>
  283. ```console
  284. npm install
  285. ```
  286. 1. Start MongoDB Lens:<br>
  287. ```console
  288. node mongodb-lens.js mongodb://older-mongodb-instance
  289. ```
  290. This will use the older driver version compatible with your MongoDB instance.
  291. > [!NOTE]<br>
  292. > 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.
  293. #### Older MongoDB Versions: Using NPX or Docker
  294. 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.
  295. 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)).
  296. To run an older version of MongoDB Lens using NPX, specify the version tag:
  297. ```console
  298. npx -y mongodb-lens@8.3.0
  299. ```
  300. Similarly for Docker:
  301. ```console
  302. docker run --rm -i --network=host furey/mongodb-lens:8.3.0
  303. ```
  304. ## Configuration
  305. - [MongoDB Connection String](#configuration-mongodb-connection-string)
  306. - [Config File](#configuration-config-file)
  307. - [Config File Generation](#configuration-config-file-generation)
  308. - [Multiple MongoDB Connections](#configuration-multiple-mongodb-connections)
  309. - [Environment Variable Overrides](#configuration-environment-variable-overrides)
  310. - [Cross-Platform Environment Variables](#configuration-cross-platform-environment-variables)
  311. ### Configuration: MongoDB Connection String
  312. The server accepts a MongoDB connection string as its only argument.
  313. Example NPX usage:
  314. ```console
  315. npx -y mongodb-lens@latest mongodb://your-connection-string
  316. ```
  317. MongoDB connection strings have the following format:
  318. ```txt
  319. mongodb://[username:password@]host[:port][/database][?options]
  320. ```
  321. Example connection strings:
  322. - Local connection:<br>
  323. `mongodb://localhost:27017`
  324. - Connection to `mydatabase` with credentials from `admin` database:<br>
  325. `mongodb://username:password@hostname:27017/mydatabase?authSource=admin`
  326. - Connection to `mydatabase` with various other options:<br>
  327. `mongodb://hostname:27017/mydatabase?retryWrites=true&w=majority`
  328. If no connection string is provided, the server will attempt to connect via local connection.
  329. ### Configuration: Config File
  330. MongoDB Lens supports extensive customization via JSON configuration file.
  331. > [!NOTE]<br>
  332. > The config file is optional. MongoDB Lens will run with default settings if no config file is provided.
  333. > [!TIP]<br>
  334. > 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.
  335. > [!TIP]<br>
  336. > MongoDB Lens supports both `.json` and `.jsonc` (JSON with comments) config file formats.
  337. <details>
  338. <summary><strong>Example configuration file</strong></summary>
  339. ```jsonc
  340. {
  341. "mongoUri": "mongodb://localhost:27017", // Default MongoDB connection string or object of alias-URI pairs
  342. "connectionOptions": {
  343. "maxPoolSize": 20, // Maximum number of connections in the pool
  344. "retryWrites": false, // Whether to retry write operations
  345. "connectTimeoutMS": 30000, // Connection timeout in milliseconds
  346. "socketTimeoutMS": 360000, // Socket timeout in milliseconds
  347. "heartbeatFrequencyMS": 10000, // How often to ping servers for status
  348. "serverSelectionTimeoutMS": 30000 // Timeout for server selection
  349. },
  350. "defaultDbName": "admin", // Default database if not specified in URI
  351. "connection": {
  352. "maxRetries": 5, // Maximum number of initial connection attempts
  353. "maxRetryDelayMs": 30000, // Maximum delay between retries
  354. "reconnectionRetries": 10, // Maximum reconnection attempts if connection lost
  355. "initialRetryDelayMs": 1000 // Initial delay between retries
  356. },
  357. "disabled": {
  358. "tools": [], // Array of tools to disable or true to disable all
  359. "prompts": [], // Array of prompts to disable or true to disable all
  360. "resources": [] // Array of resources to disable or true to disable all
  361. },
  362. "enabled": {
  363. "tools": true, // Array of tools to enable or true to enable all
  364. "prompts": true, // Array of prompts to enable or true to enable all
  365. "resources": true // Array of resources to enable or true to enable all
  366. },
  367. "cacheTTL": {
  368. "stats": 15000, // Stats cache lifetime in milliseconds
  369. "fields": 30000, // Fields cache lifetime in milliseconds
  370. "schemas": 60000, // Schema cache lifetime in milliseconds
  371. "indexes": 120000, // Index cache lifetime in milliseconds
  372. "collections": 30000, // Collections list cache lifetime in milliseconds
  373. "serverStatus": 20000 // Server status cache lifetime in milliseconds
  374. },
  375. "enabledCaches": [ // List of caches to enable
  376. "stats", // Statistics cache
  377. "fields", // Collection fields cache
  378. "schemas", // Collection schemas cache
  379. "indexes", // Collection indexes cache
  380. "collections", // Database collections cache
  381. "serverStatus" // MongoDB server status cache
  382. ],
  383. "memory": {
  384. "enableGC": true, // Whether to enable garbage collection
  385. "warningThresholdMB": 1500, // Memory threshold for warnings
  386. "criticalThresholdMB": 2000 // Memory threshold for cache clearing
  387. },
  388. "logLevel": "info", // Log level (info or verbose)
  389. "disableDestructiveOperationTokens": false, // Whether to skip confirmation for destructive ops
  390. "watchdogIntervalMs": 30000, // Interval for connection monitoring
  391. "defaults": {
  392. "slowMs": 100, // Threshold for slow query detection
  393. "queryLimit": 10, // Default limit for query results
  394. "allowDiskUse": true, // Allow operations to use disk for large datasets
  395. "schemaSampleSize": 100, // Sample size for schema inference
  396. "aggregationBatchSize": 50 // Batch size for aggregation operations
  397. },
  398. "security": {
  399. "tokenLength": 4, // Length of confirmation tokens
  400. "tokenExpirationMinutes": 5, // Expiration time for tokens
  401. "strictDatabaseNameValidation": true // Enforce strict database name validation
  402. },
  403. "tools": {
  404. "transaction": {
  405. "readConcern": "snapshot", // Read concern level for transactions
  406. "writeConcern": {
  407. "w": "majority" // Write concern for transactions
  408. }
  409. },
  410. "bulkOperations": {
  411. "ordered": true // Whether bulk operations execute in order
  412. },
  413. "export": {
  414. "defaultLimit": -1, // Default limit for exports (-1 = no limit)
  415. "defaultFormat": "json" // Default export format (json or csv)
  416. },
  417. "watchChanges": {
  418. "maxDurationSeconds": 60, // Maximum duration for change streams
  419. "defaultDurationSeconds": 10 // Default duration for change streams
  420. },
  421. "queryAnalysis": {
  422. "defaultDurationSeconds": 10 // Default duration for query analysis
  423. }
  424. }
  425. }
  426. ```
  427. </details>
  428. By default, MongoDB Lens looks for the config file at:
  429. - `~/.mongodb-lens.jsonc` first, then falls back to
  430. - `~/.mongodb-lens.json` if the former doesn't exist
  431. To customize the config file path, set the environment variable `CONFIG_PATH` to the desired file path.
  432. Example NPX usage:
  433. ```console
  434. CONFIG_PATH='/path/to/config.json' npx -y mongodb-lens@latest
  435. ```
  436. Example Docker Hub usage:
  437. ```console
  438. docker run --rm -i --network=host --pull=always -v /path/to/config.json:/root/.mongodb-lens.json furey/mongodb-lens
  439. ```
  440. ### Configuration: Config File Generation
  441. You can generate a configuration file automatically using the `config:create` script:
  442. ```console
  443. # NPX Usage (recommended)
  444. npx -y mongodb-lens@latest config:create
  445. # Node.js Usage
  446. npm run config:create
  447. # Force overwrite existing files
  448. npx -y mongodb-lens@latest config:create -- --force
  449. npm run config:create -- --force
  450. ```
  451. This script extracts the [example configuration file](#configuration-config-file) above and saves it to: `~/.mongodb-lens.jsonc`
  452. #### Config File Generation: Custom Path
  453. You can specify a custom output location using the `CONFIG_PATH` environment variable.
  454. - If `CONFIG_PATH` has no file extension, it's treated as a directory and `.mongodb-lens.jsonc` is appended
  455. - If `CONFIG_PATH` ends with `.json` (not `.jsonc`) comments are removed from the generated file
  456. Example NPX usage:
  457. ```console
  458. # With custom path
  459. CONFIG_PATH=/path/to/config.jsonc npx -y mongodb-lens@latest config:create
  460. # Save to directory (will append .mongodb-lens.jsonc to the path)
  461. CONFIG_PATH=/path/to/directory npx -y mongodb-lens@latest config:create
  462. # Save as JSON instead of JSONC
  463. CONFIG_PATH=/path/to/config.json npx -y mongodb-lens@latest config:create
  464. ```
  465. Example Node.js usage:
  466. ```console
  467. # With custom path
  468. CONFIG_PATH=/path/to/config.jsonc node mongodb-lens.js config:create
  469. # Save to directory (will append .mongodb-lens.jsonc to the path)
  470. CONFIG_PATH=/path/to/directory node mongodb-lens.js config:create
  471. # Save as JSON instead of JSONC
  472. CONFIG_PATH=/path/to/config.json node mongodb-lens.js config:create
  473. ```
  474. ### Configuration: Multiple MongoDB Connections
  475. 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.
  476. To configure multiple connections, set the `mongoUri` config setting to an object with alias-URI pairs:
  477. ```json
  478. {
  479. "mongoUri": {
  480. "main": "mongodb://localhost:27017",
  481. "backup": "mongodb://localhost:27018",
  482. "atlas": "mongodb+srv://username:password@cluster.mongodb.net/mydb"
  483. }
  484. }
  485. ```
  486. With this configuration:
  487. - The first URI in the list (e.g. `main`) becomes the default connection at startup
  488. - You can switch connections using natural language: `"Connect to backup"` or `"Connect to atlas"`
  489. - The original syntax still works: `"Connect to mongodb://localhost:27018"`
  490. - The `list-connections` tool shows all available connection aliases
  491. > [!NOTE]<br>
  492. > 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.
  493. > [!TIP]<br>
  494. > To add connection aliases at runtime, use the `add-connection-alias` tool.
  495. ### Configuration: Environment Variable Overrides
  496. MongoDB Lens supports environment variable overrides for configuration settings.
  497. Environment variables take precedence over [config file](#configuration-config-file) settings.
  498. Config environment variables follow the naming pattern:
  499. ```txt
  500. CONFIG_[SETTING PATH, SNAKE CASED, UPPERCASED]
  501. ```
  502. Example overrides:
  503. | Config Setting | Environment Variable Override |
  504. | -------------------------------- | ----------------------------------------- |
  505. | `mongoUri` | `CONFIG_MONGO_URI` |
  506. | `logLevel` | `CONFIG_LOG_LEVEL` |
  507. | `defaultDbName` | `CONFIG_DEFAULT_DB_NAME` |
  508. | `defaults.queryLimit` | `CONFIG_DEFAULTS_QUERY_LIMIT` |
  509. | `tools.export.defaultFormat` | `CONFIG_TOOLS_EXPORT_DEFAULT_FORMAT` |
  510. | `connectionOptions.maxPoolSize` | `CONFIG_CONNECTION_OPTIONS_MAX_POOL_SIZE` |
  511. | `connection.reconnectionRetries` | `CONFIG_CONNECTION_RECONNECTION_RETRIES` |
  512. For environment variable values:
  513. - For boolean settings, use string values `'true'` or `'false'`.
  514. - For numeric settings, use string representations.
  515. - For nested objects or arrays, use JSON strings.
  516. Example NPX usage:
  517. ```console
  518. CONFIG_DEFAULTS_QUERY_LIMIT='25' npx -y mongodb-lens@latest
  519. ```
  520. Example Docker Hub usage:
  521. ```console
  522. docker run --rm -i --network=host --pull=always -e CONFIG_DEFAULTS_QUERY_LIMIT='25' furey/mongodb-lens
  523. ```
  524. ### Configuration: Cross-Platform Environment Variables
  525. For consistent environment variable usage across Windows, macOS, and Linux, consider using `cross-env`:
  526. 1. Install cross-env globally:<br>
  527. ```console
  528. # Using NPM
  529. npm install -g cross-env
  530. # Using Volta (see: https://volta.sh)
  531. volta install cross-env
  532. ```
  533. 1. Prefix any NPX or Node.js environment variables in this document's examples:<br>
  534. ```console
  535. # Example NPX usage with cross-env
  536. cross-env CONFIG_DEFAULTS_QUERY_LIMIT='25' npx -y mongodb-lens@latest
  537. # Example Node.js usage with cross-env
  538. cross-env CONFIG_DEFAULTS_QUERY_LIMIT='25' node mongodb-lens.js
  539. ```
  540. ## Client Setup
  541. - [Claude Desktop](#client-setup-claude-desktop)
  542. - [MCP Inspector](#client-setup-mcp-inspector)
  543. - [Other MCP Clients](#client-setup-other-mcp-clients)
  544. ### Client Setup: Claude Desktop
  545. To use MongoDB Lens with Claude Desktop:
  546. 1. Install [Claude Desktop](https://claude.ai/download)
  547. 1. Open `claude_desktop_config.json` (create if it doesn't exist):
  548. - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
  549. - Windows: `%APPDATA%\Claude\claude_desktop_config.json`
  550. 1. Add the MongoDB Lens server configuration as per [configuration options](#claude-desktop-configuration-options)
  551. 1. Restart Claude Desktop
  552. 1. Start a conversation with Claude about your MongoDB data
  553. #### Claude Desktop Configuration Options
  554. - [Option 1: NPX (Recommended)](#option-1-npx-recommended)
  555. - [Option 2: Docker Hub Image](#option-2-docker-hub-image)
  556. - [Option 3: Local Node.js Installation](#option-3-local-nodejs-installation)
  557. - [Option 4: Local Docker Image](#option-4-local-docker-image)
  558. For each option:
  559. - Replace `mongodb://your-connection-string` with your MongoDB connection string or omit it to use the default `mongodb://localhost:27017`.
  560. - To use a custom config file, set [`CONFIG_PATH`](#configuration-config-file) environment variable.
  561. - To include environment variables:
  562. - For NPX or Node.js add `"env": {}` with key-value pairs, for example:<br>
  563. ```json
  564. "command": "/path/to/npx",
  565. "args": [
  566. "-y",
  567. "mongodb-lens@latest",
  568. "mongodb://your-connection-string"
  569. ],
  570. "env": {
  571. "CONFIG_LOG_LEVEL": "verbose"
  572. }
  573. ```
  574. - For Docker add `-e` flags, for example:<br>
  575. ```json
  576. "command": "docker",
  577. "args": [
  578. "run", "--rm", "-i",
  579. "--network=host",
  580. "--pull=always",
  581. "-e", "CONFIG_LOG_LEVEL=verbose",
  582. "furey/mongodb-lens",
  583. "mongodb://your-connection-string"
  584. ]
  585. ```
  586. ##### Option 1: NPX (Recommended)
  587. ```json
  588. {
  589. "mcpServers": {
  590. "mongodb-lens": {
  591. "command": "/path/to/npx",
  592. "args": [
  593. "-y",
  594. "mongodb-lens@latest",
  595. "mongodb://your-connection-string"
  596. ]
  597. }
  598. }
  599. }
  600. ```
  601. ##### Option 2: Docker Hub Image
  602. ```json
  603. {
  604. "mcpServers": {
  605. "mongodb-lens": {
  606. "command": "docker",
  607. "args": [
  608. "run", "--rm", "-i",
  609. "--network=host",
  610. "--pull=always",
  611. "furey/mongodb-lens",
  612. "mongodb://your-connection-string"
  613. ]
  614. }
  615. }
  616. }
  617. ```
  618. ##### Option 3: Local Node.js Installation
  619. ```json
  620. {
  621. "mcpServers": {
  622. "mongodb-lens": {
  623. "command": "/path/to/node",
  624. "args": [
  625. "/path/to/mongodb-lens.js",
  626. "mongodb://your-connection-string"
  627. ]
  628. }
  629. }
  630. }
  631. ```
  632. ##### Option 4: Local Docker Image
  633. ```json
  634. {
  635. "mcpServers": {
  636. "mongodb-lens": {
  637. "command": "docker",
  638. "args": [
  639. "run", "--rm", "-i",
  640. "--network=host",
  641. "mongodb-lens",
  642. "mongodb://your-connection-string"
  643. ]
  644. }
  645. }
  646. }
  647. ```
  648. ### Client Setup: MCP Inspector
  649. [MCP Inspector](https://github.com/modelcontextprotocol/inspector) is a tool designed for testing and debugging MCP servers.
  650. > [!NOTE]<br>
  651. > MCP Inspector starts a proxy server on port 3000 and web client on port 5173.
  652. Example NPX usage:
  653. 1. Run MCP Inspector:<br>
  654. ```console
  655. # Using default connection string mongodb://localhost:27017
  656. npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest
  657. # Using custom connection string
  658. npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest mongodb://your-connection-string
  659. # Using custom ports
  660. SERVER_PORT=1234 CLIENT_PORT=5678 npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest
  661. ```
  662. 1. Open MCP Inspector: http://localhost:5173
  663. MCP Inspector should support the full range of MongoDB Lens capabilities, including autocompletion for collection names and query fields.
  664. For more, see: [MCP Inspector](https://modelcontextprotocol.io/docs/tools/inspector)
  665. ### Client Setup: Other MCP Clients
  666. MongoDB Lens should be usable with any MCP-compatible client.
  667. For more, see: [MCP Documentation: Example Clients](https://modelcontextprotocol.io/clients)
  668. ## Data Protection
  669. To protect your data while using MongoDB Lens, consider the following:
  670. - [Read-Only User Accounts](#data-protection-read-only-user-accounts)
  671. - [Working with Database Backups](#data-protection-working-with-database-backups)
  672. - [Data Flow Considerations](#data-protection-data-flow-considerations)
  673. - [Confirmation for Destructive Operations](#data-protection-confirmation-for-destructive-operations)
  674. - [Disabling Destructive Operations](#data-protection-disabling-destructive-operations)
  675. ### Data Protection: Read-Only User Accounts
  676. 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.
  677. 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:
  678. ```js
  679. use admin
  680. db.createUser({
  681. user: 'readonly',
  682. pwd: 'eXaMpLePaSsWoRd',
  683. roles: [{ role: 'read', db: 'mydatabase' }]
  684. })
  685. ```
  686. Then, apply those credentials to your MongoDB connection string:
  687. ```txt
  688. mongodb://readonly:eXaMpLePaSsWoRd@localhost:27017/mydatabase
  689. ```
  690. 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.
  691. ### Data Protection: Working with Database Backups
  692. When working with MongoDB Lens, consider connecting to a backup copy of your data hosted on a separate MongoDB instance.
  693. 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`).
  694. This approach gives you a sandbox to test complex or destructive operations against without risking accidental corruption of your live data.
  695. ### Data Protection: Data Flow Considerations
  696. - [How Your Data Flows Through the System](#data-flow-considerations-how-your-data-flows-through-the-system)
  697. - [Protecting Sensitive Data with Projection](#data-flow-considerations-protecting-sensitive-data-with-projection)
  698. - [Connection Aliases and Passwords](#data-flow-considerations-connection-aliases-and-passwords)
  699. - [Local Setup for Maximum Safety](#data-flow-considerations-local-setup-for-maximum-safety)
  700. #### Data Flow Considerations: How Your Data Flows Through the System
  701. 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.
  702. When you send a MongoDB related query through your MCP client, here’s what happens:
  703. > [!NOTE]<br>
  704. > While this example uses a local MongoDB instance, the same principles apply to remote MongoDB instances.
  705. ```mermaid
  706. sequenceDiagram
  707. actor User
  708. box Local Machine #d4f1f9
  709. participant Client as MCP Client
  710. participant Lens as MongoDB Lens
  711. participant MongoDB as MongoDB Instance
  712. end
  713. box Remote Server #ffe6cc
  714. participant LLM as Remote LLM Provider
  715. end
  716. User->>Client: 1. Submit request<br>"Show me all users older than 30"
  717. Client->>LLM: 2. User request + available tools
  718. Note over LLM: Interprets request<br>Chooses appropriate tool
  719. LLM->>Client: 3. Tool selection (find-documents)
  720. Client->>Lens: 4. Tool run with parameters
  721. Lens->>MongoDB: 5. Database query
  722. MongoDB-->>Lens: 6. Database results
  723. Lens-->>Client: 7. Tool results (formatted data)
  724. Client->>LLM: 8. Tool results
  725. Note over LLM: Processes results<br>Formats response
  726. LLM-->>Client: 9. Processed response
  727. Client-->>User: 10. Final answer
  728. ```
  729. 1. You submit a request<br><sup>➥ e.g. "Show me all users older than 30"</sup>
  730. 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>
  731. 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>
  732. 1. The client asks MongoDB Lens to run the tool<br><sup>➥ This occurs locally on your machine via stdio.</sup>
  733. 1. MongoDB Lens queries your MongoDB database
  734. 1. MongoDB Lens retrieves your MongoDB query results
  735. 1. MongoDB Lens sends the data back to the client<br><sup>➥ The client receives results formatted by MongoDB Lens.</sup>
  736. 1. The client forwards the data to the remote LLM<br><sup>➥ The LLM provider sees the exact data returned by MongoDB Lens.</sup>
  737. 1. The remote LLM processes the data<br><sup>➥ It may summarize or format the results further.</sup>
  738. 1. The remote LLM sends the final response to the client<br><sup>➥ The client displays the answer to you.</sup>
  739. 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.
  740. #### Data Flow Considerations: Protecting Sensitive Data with Projection
  741. 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.
  742. Example projection usage:
  743. - _"Show me all users older than 30, but use projection to hide their passwords."_<br>
  744. <sup>➥ Uses `find-documents` tool with projection</sup>
  745. #### Data Flow Considerations: Connection Aliases and Passwords
  746. 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.
  747. #### Data Flow Considerations: Local Setup for Maximum Safety
  748. 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.
  749. ### Data Protection: Confirmation for Destructive Operations
  750. 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:
  751. 1. First tool invocation: Returns a 4-digit confirmation token that expires after 5 minutes
  752. 1. Second tool invocation: Executes the operation if provided with the valid token
  753. For an example of the confirmation process, see: [Working with Confirmation Protection](#tutorial-5-working-with-confirmation-protection)
  754. Tools that require confirmation include:
  755. - `drop-user`: Remove a database user
  756. - `drop-index`: Remove an index (potential performance impact)
  757. - `drop-database`: Permanently delete a database
  758. - `drop-collection`: Delete a collection and all its documents
  759. - `delete-document`: Delete one or multiple documents
  760. - `bulk-operations`: When including delete operations
  761. - `rename-collection`: When the target collection exists and will be dropped
  762. 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.
  763. > [!NOTE]<br>
  764. > 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.
  765. #### Bypassing Confirmation for Destructive Operations
  766. You might want to bypass the token confirmation system.
  767. Set the environment variable `CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS` to `true` to execute destructive operations immediately without confirmation:
  768. ```console
  769. # Using NPX
  770. CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS=true npx -y mongodb-lens@latest
  771. # Using Docker
  772. docker run --rm -i --network=host --pull=always -e CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS='true' furey/mongodb-lens
  773. ```
  774. > [!WARNING]<br>
  775. > 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.
  776. ### Data Protection: Disabling Destructive Operations
  777. - [Disabling Tools](#disabling-tools)
  778. - [High-Risk Tools](#high-risk-tools)
  779. - [Medium-Risk Tools](#medium-risk-tools)
  780. - [Read-Only Configuration](#read-only-configuration)
  781. - [Selective Component Enabling](#selective-component-enabling)
  782. #### Disabling Tools
  783. 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):
  784. ```json
  785. {
  786. "disabled": {
  787. "tools": [
  788. "drop-user",
  789. "drop-index",
  790. "drop-database",
  791. "drop-collection",
  792. "delete-document",
  793. "bulk-operations",
  794. "rename-collection"
  795. ]
  796. }
  797. }
  798. ```
  799. > [!NOTE]<br>
  800. > Resources and prompts can also be disabled via `disabled.resources` and `disabled.prompts` settings.
  801. #### High-Risk Tools
  802. These tools can cause immediate data loss and should be considered for disabling in sensitive environments:
  803. - `drop-user`: Removes database users and their access permissions
  804. - `drop-index`: Removes indexes (can impact query performance)
  805. - `drop-database`: Permanently deletes entire databases
  806. - `drop-collection`: Permanently deletes collections and all their documents
  807. - `delete-document`: Removes documents matching specified criteria
  808. - `bulk-operations`: Can perform batch deletions when configured to do so
  809. - `rename-collection`: Can overwrite existing collections when using the drop target option
  810. #### Medium-Risk Tools
  811. These tools can modify data but typically don't cause immediate data loss:
  812. - `create-user`: Creates users with permissions that could enable further changes
  813. - `transaction`: Executes multiple operations in a transaction (potential for complex changes)
  814. - `update-document`: Updates documents which could overwrite existing data
  815. #### Read-Only Configuration
  816. For a complete read-only configuration, disable all potentially destructive tools:
  817. ```json
  818. {
  819. "disabled": {
  820. "tools": [
  821. "drop-user",
  822. "drop-index",
  823. "create-user",
  824. "transaction",
  825. "create-index",
  826. "drop-database",
  827. "drop-collection",
  828. "insert-document",
  829. "update-document",
  830. "delete-document",
  831. "bulk-operations",
  832. "create-database",
  833. "gridfs-operation",
  834. "create-collection",
  835. "rename-collection",
  836. "create-timeseries"
  837. ]
  838. }
  839. }
  840. ```
  841. This configuration allows MongoDB Lens to query and analyze data while preventing any modifications, providing multiple layers of protection against accidental data loss.
  842. #### Selective Component Enabling
  843. 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):
  844. ```json
  845. {
  846. "enabled": {
  847. "tools": [
  848. "use-database",
  849. "find-documents",
  850. "count-documents",
  851. "aggregate-data"
  852. ]
  853. },
  854. "disabled": {
  855. "resources": true,
  856. "prompts": true
  857. }
  858. }
  859. ```
  860. > [!IMPORTANT]<br>
  861. > If a component appears in both `enabled` and `disabled` lists, the `enabled` setting takes precedence.
  862. ## Tutorial
  863. 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:
  864. 1. [Start Sample Data Container](#tutorial-1-start-sample-data-container)
  865. 1. [Import Sample Data](#tutorial-2-import-sample-data)
  866. 1. [Connect MongoDB Lens](#tutorial-3-connect-mongodb-lens)
  867. 1. [Example Queries](#tutorial-4-example-queries)
  868. 1. [Working With Confirmation Protection](#tutorial-5-working-with-confirmation-protection)
  869. ### Tutorial: 1. Start Sample Data Container
  870. > [!NOTE]<br>
  871. > This tutorial assumes you have [Docker](https://docs.docker.com/get-started/get-docker/) installed and running on your system.
  872. > [!IMPORTANT]<br>
  873. > If Docker is already running a container on port 27017, stop it before proceeding.
  874. 1. Initialise the sample data container:<br>
  875. ```console
  876. docker run --name mongodb-sampledata -d -p 27017:27017 mongo:6
  877. ```
  878. 1. Verify the container is running without issue:<br>
  879. ```console
  880. docker ps | grep mongodb-sampledata
  881. ```
  882. ### Tutorial: 2. Import Sample Data
  883. MongoDB provides several [sample datasets](https://www.mongodb.com/docs/atlas/sample-data/#available-sample-datasets) which we'll use to explore MongoDB Lens.
  884. 1. Download the sample datasets:
  885. ```console<br>
  886. curl -LO https://atlas-education.s3.amazonaws.com/sampledata.archive
  887. ```
  888. 1. Copy the sample datasets into your sample data container:<br>
  889. ```console
  890. docker cp sampledata.archive mongodb-sampledata:/tmp/
  891. ```
  892. 1. Import the sample datasets into MongoDB:<br>
  893. ```console
  894. docker exec -it mongodb-sampledata mongorestore --archive=/tmp/sampledata.archive
  895. ```
  896. This will import several databases:
  897. - `sample_airbnb`: Airbnb listings and reviews
  898. - `sample_analytics`: Customer and account data
  899. - `sample_geospatial`: Geographic data
  900. - `sample_mflix`: Movie data
  901. - `sample_restaurants`: Restaurant data
  902. - `sample_supplies`: Supply chain data
  903. - `sample_training`: Training data for various applications
  904. - `sample_weatherdata`: Weather measurements
  905. ### Tutorial: 3. Connect MongoDB Lens
  906. [Install](#installation) MongoDB Lens as per the [Quick Start](#quick-start) instructions.
  907. Set your [MCP Client](#client-setup) to connect to MongoDB Lens via: `mongodb://localhost:27017`
  908. > [!TIP]<br>
  909. > Omitting the connection string from your MCP Client configuration will default the connection string to `mongodb://localhost:27017`.
  910. Example [Claude Desktop configuration](#client-setup-claude-desktop):
  911. ```json
  912. {
  913. "mcpServers": {
  914. "mongodb-lens": {
  915. "command": "/path/to/npx",
  916. "args": [
  917. "-y",
  918. "mongodb-lens@latest"
  919. ]
  920. }
  921. }
  922. }
  923. ```
  924. ### Tutorial: 4. Example Queries
  925. With your MCP Client running and connected to MongoDB Lens, try the following example queries:
  926. - [Example Queries: Basic Database Operations](#example-queries-basic-database-operations)
  927. - [Example Queries: Collection Management](#example-queries-collection-management)
  928. - [Example Queries: User Management](#example-queries-user-management)
  929. - [Example Queries: Querying Data](#example-queries-querying-data)
  930. - [Example Queries: Schema Analysis](#example-queries-schema-analysis)
  931. - [Example Queries: Data Modification](#example-queries-data-modification)
  932. - [Example Queries: Performance & Index Management](#example-queries-performance--index-management)
  933. - [Example Queries: Geospatial & Special Operations](#example-queries-geospatial--special-operations)
  934. - [Example Queries: Export, Administrative & Other Features](#example-queries-export-administrative--other-features)
  935. - [Example Queries: Connection Management](#example-queries-connection-management)
  936. #### Example Queries: Basic Database Operations
  937. - _"List all databases"_<br>
  938. <sup>➥ Uses `list-databases` tool</sup>
  939. - _"What db am I currently using?"_<br>
  940. <sup>➥ Uses `current-database` tool</sup>
  941. - _"Switch to the sample_mflix database"_<br>
  942. <sup>➥ Uses `use-database` tool</sup>
  943. - _"Create a new db called test_db"_<br>
  944. <sup>➥ Uses `create-database` tool</sup>
  945. - _"Create another db called analytics_db and switch to it"_<br>
  946. <sup>➥ Uses `create-database` tool with switch=true</sup>
  947. - _"Drop test_db"_<br>
  948. <sup>➥ Uses `drop-database` tool (with confirmation)</sup>
  949. #### Example Queries: Collection Management
  950. - _"What collections are in the current database?"_<br>
  951. <sup>➥ Uses `list-collections` tool</sup>
  952. - _"Create user_logs collection"_<br>
  953. <sup>➥ Uses `create-collection` tool</sup>
  954. - _"Rename user_logs to system_logs"_<br>
  955. <sup>➥ Uses `rename-collection` tool</sup>
  956. - _"Drop system_logs"_<br>
  957. <sup>➥ Uses `drop-collection` tool (with confirmation)</sup>
  958. - _"Check the data consistency in the movies collection"_<br>
  959. <sup>➥ Uses `validate-collection` tool</sup>
  960. #### Example Queries: User Management
  961. - _"Create a read-only user for analytics"_<br>
  962. <sup>➥ Uses `create-user` tool</sup>
  963. - _"Drop the inactive_user account"_<br>
  964. <sup>➥ Uses `drop-user` tool (with confirmation)</sup>
  965. #### Example Queries: Querying Data
  966. - _"Count all docs in the movies collection"_<br>
  967. <sup>➥ Uses `count-documents` tool</sup>
  968. - _"Find the top 5 movies with the highest IMDB rating"_<br>
  969. <sup>➥ Uses `find-documents` tool</sup>
  970. - _"Show me aggregate data for movies grouped by decade"_<br>
  971. <sup>➥ Uses `aggregate-data` tool</sup>
  972. - _"List all unique countries where movies were produced"_<br>
  973. <sup>➥ Uses `distinct-values` tool</sup>
  974. - _"Search for movies containing godfather in their title"_<br>
  975. <sup>➥ Uses `text-search` tool</sup>
  976. - _"Find German users with last name müller using proper collation"_<br>
  977. <sup>➥ Uses `collation-query` tool</sup>
  978. #### Example Queries: Schema Analysis
  979. - _"What's the schema structure of the movies collection?"_<br>
  980. <sup>➥ Uses `analyze-schema` tool</sup>
  981. - _"Compare users and comments schemas"_<br>
  982. <sup>➥ Uses `compare-schemas` tool</sup>
  983. - _"Generate a schema validator for the movies collection"_<br>
  984. <sup>➥ Uses `generate-schema-validator` tool</sup>
  985. - _"Analyze common query patterns for the movies collection"_<br>
  986. <sup>➥ Uses `analyze-query-patterns` tool</sup>
  987. #### Example Queries: Data Modification
  988. - _"Insert new movie document: \<your field data\>"_<br>
  989. <sup>➥ Uses `insert-document` tool</sup>
  990. - _"Update all movies from 1994 to add a 'classic' flag"_<br>
  991. <sup>➥ Uses `update-document` tool</sup>
  992. - _"Delete all movies with zero ratings"_<br>
  993. <sup>➥ Uses `delete-document` tool (with confirmation)</sup>
  994. - _"Run these bulk operations on the movies collection: \<your JSON data\>"_<br>
  995. <sup>➥ Uses `bulk-operations` tool</sup>
  996. > [!TIP]<br>
  997. > 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.
  998. #### Example Queries: Performance & Index Management
  999. - _"Create an index on the title field in the movies collection"_<br>
  1000. <sup>➥ Uses `create-index` tool</sup>
  1001. - _"Drop the ratings_idx index"_<br>
  1002. <sup>➥ Uses `drop-index` tool (with confirmation)</sup>
  1003. - _"Explain the execution plan for finding movies from 1995"_<br>
  1004. <sup>➥ Uses `explain-query` tool</sup>
  1005. - _"Get statistics for the current db"_<br>
  1006. <sup>➥ Uses `get-stats` tool with target=database</sup>
  1007. - _"Show collection stats for the movies collection"_<br>
  1008. <sup>➥ Uses `get-stats` tool with target=collection</sup>
  1009. #### Example Queries: Geospatial & Special Operations
  1010. - _"Switch to sample_geospatial db, then find all shipwrecks within 10km of coordinates [-80.12, 26.46]"_<br>
  1011. <sup>➥ Uses `geo-query` tool</sup>
  1012. - _"Switch to sample_analytics db, then execute a transaction to move funds between accounts: \<account ids\>"_<br>
  1013. <sup>➥ Uses `transaction` tool</sup>
  1014. - _"Create a time series collection for sensor readings"_<br>
  1015. <sup>➥ Uses `create-timeseries` tool</sup>
  1016. - _"Watch for changes in the users collection for 30 seconds"_<br>
  1017. <sup>➥ Uses `watch-changes` tool</sup>
  1018. - _"List all files in the images GridFS bucket"_<br>
  1019. <sup>➥ Uses `gridfs-operation` tool with operation=list</sup>
  1020. #### Example Queries: Export, Administrative & Other Features
  1021. - _"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>
  1022. <sup>➥ Uses `export-data` tool</sup>
  1023. - _"Switch to sample_analytics db, then check its sharding status"_<br>
  1024. <sup>➥ Uses `shard-status` tool</sup>
  1025. - _"Clear the collections cache"_<br>
  1026. <sup>➥ Uses `clear-cache` tool with target=collections</sup>
  1027. - _"Clear all caches"_<br>
  1028. <sup>➥ Uses `clear-cache` tool</sup>
  1029. - _"Switch to sample_weatherdata db then generate an interactive report on its current state"_<br>
  1030. <sup>➥ Uses numerous tools</sup>
  1031. #### Example Queries: Connection Management
  1032. - _"Connect to mongodb://localhost:27018"_<br>
  1033. <sup>➥ Uses `connect-mongodb` tool</sup>
  1034. - _"Connect to mongodb+srv://username:password@cluster.mongodb.net/mydb"_<br>
  1035. <sup>➥ Uses `connect-mongodb` tool</sup>
  1036. - _"Connect back to the original mongodb instance"_<br>
  1037. <sup>➥ Uses `connect-original` tool</sup>
  1038. - _"Connect to replica set without validating the connection: \<replica set details\>"_<br>
  1039. <sup>➥ Uses `connect-mongodb` tool with validateConnection=false</sup>
  1040. - _"Add connection alias 'prod' for mongodb://username:password@prod-server:27017/mydb"_<br>
  1041. <sup>➥ Uses `add-connection-alias` tool</sup>
  1042. ### Tutorial: 5. Working With Confirmation Protection
  1043. MongoDB Lens includes a safety mechanism for potentially destructive operations. Here's how it works in practice:
  1044. 1. Request to drop a collection:<br>
  1045. ```
  1046. "Drop the collection named test_collection"
  1047. ```
  1048. 1. MongoDB Lens responds with a warning and confirmation token:<br>
  1049. ```
  1050. ⚠️ DESTRUCTIVE OPERATION WARNING ⚠️
  1051. You've requested to drop the collection 'test_collection'.
  1052. This operation is irreversible and will permanently delete all data in this collection.
  1053. To confirm, you must type the 4-digit confirmation code EXACTLY as shown below:
  1054. Confirmation code: 9876
  1055. This code will expire in 5 minutes for security purposes.
  1056. ```
  1057. 1. Confirm the operation by submitting the confirmation token:<br>
  1058. ```
  1059. "9876"
  1060. ```
  1061. 1. MongoDB Lens executes the operation:<br>
  1062. ```
  1063. Collection 'test_collection' has been permanently deleted.
  1064. ```
  1065. This two-step process prevents accidental data loss by requiring explicit confirmation.
  1066. > [!NOTE]<br>
  1067. > 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.
  1068. ## Test Suite
  1069. MongoDB Lens includes a [test suite](./mongodb-lens.test.js) to verify functionality across tools, resources, and prompts.
  1070. - [Running Tests](#test-suite-running-tests)
  1071. - [Command Line Options](#test-suite-command-line-options)
  1072. - [Examples](#test-suite-examples)
  1073. ### Test Suite: Running Tests
  1074. The test suite requires a `CONFIG_MONGO_URI` environment variable which can be set to:
  1075. - a MongoDB connection string (e.g. `mongodb://localhost:27017`)
  1076. - `mongodb-memory-server` (for in-memory testing)
  1077. ```console
  1078. # Run Tests with MongoDB Connection String
  1079. CONFIG_MONGO_URI=mongodb://localhost:27017 node mongodb-lens.test.js
  1080. # Run Tests with In-Memory MongoDB (requires mongodb-memory-server)
  1081. CONFIG_MONGO_URI=mongodb-memory-server node mongodb-lens.test.js
  1082. ```
  1083. For convenience, the following scripts are available for running tests:
  1084. ```console
  1085. npm test # Fails if no CONFIG_MONGO_URI provided
  1086. npm run test:localhost # Uses mongodb://localhost:27017
  1087. npm run test:localhost:verbose # Runs with DEBUG=true for verbose output
  1088. npm run test:in-memory # Uses mongodb-memory-server
  1089. npm run test:in-memory:verbose # Runs with DEBUG=true for verbose output
  1090. ```
  1091. > [!NOTE]<br>
  1092. > The test suite creates temporary databases and collections that are cleaned up after test completion.
  1093. ### Test Suite: Command Line Options
  1094. | Option | Description |
  1095. | ------------------ | ---------------------------------------------------- |
  1096. | `--list` | List all available tests without running them |
  1097. | `--test=<n>` | Run specific test(s) by name (comma-separated) |
  1098. | `--group=<n>` | Run all tests in specific group(s) (comma-separated) |
  1099. | `--pattern=<glob>` | Run tests matching pattern(s) (comma-separated) |
  1100. ### Test Suite: Examples
  1101. ```console
  1102. # List All Available Tests
  1103. npm test -- --list
  1104. # Run Only Connection-Related Tests (:27017)
  1105. npm run test:localhost -- --group=Connection\ Tools
  1106. # Test Specific Database Operations (In-Memory)
  1107. npm run test:in-memory -- --test=create-database\ Tool,drop-database\ Tool
  1108. # Test All Document-Related Tools (:27017)
  1109. npm run test:localhost -- --pattern=document
  1110. # Run Resource Tests Only (In-Memory)
  1111. npm run test:in-memory -- --group=Resources
  1112. # Run Specific Tests Only (In-Memory)
  1113. npm run test:in-memory -- --test=aggregate-data\ Tool,find-documents\ Tool
  1114. ```
  1115. ## Disclaimer
  1116. MongoDB Lens:
  1117. - is licensed under the [MIT License](./LICENSE).
  1118. - is not affiliated with or endorsed by MongoDB, Inc.
  1119. - is written with the assistance of AI and may contain errors.
  1120. - is intended for educational and experimental purposes only.
  1121. - is provided as-is with no warranty—please use at your own risk.
  1122. ## Support
  1123. If you've found MongoDB Lens helpful consider supporting my work through:
  1124. [Buy Me a Coffee](https://www.buymeacoffee.com/furey) | [GitHub Sponsorship](https://github.com/sponsors/furey)
  1125. 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.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.