mongodb lens.com
mongodb lens.com logo

MongoDB Lens

Integrates with MongoDB databases to enable browsing collections, executing queries, running aggregation pipelines, anal...

Created byApr 22, 2025

MongoDB Lens

MongoDB Lens is a local Model Context Protocol (MCP) server with full featured access to MongoDB databases using natural language via LLMs to perform queries, run aggregations, optimize performance, and more.

Contents

  • Quick Start
  • Features
  • Installation
  • Configuration
  • Client Setup
  • Data Protection
  • Tutorial
  • Test Suite
  • Disclaimer
  • Support

Quick Start

  • Install MongoDB Lens
  • Configure MongoDB Lens
  • Set up your MCP Client (e.g. Claude Desktop, Cursor, etc)
  • Explore your MongoDB databases with natural language queries

Features

  • Tools
  • Resources
  • Prompts
  • Other

Tools

  • `bulk-operations`: Perform multiple operations efficiently (requires confirmation for destructive operations)
  • `delete-document`: Delete documents matching specified criteria (requires confirmation)
  • `drop-index`: Remove indexes from collections (requires confirmation)
  • `drop-user`: Remove database users (requires confirmation)
  • `geo-query`: Perform geospatial queries with various operators
  • `get-stats`: Retrieve database or collection statistics
  • `shard-status`: View sharding configuration for databases and collections
  • `text-search`: Perform full-text search across text-indexed fields
  • `transaction`: Execute multiple operations in a single ACID transaction

Resources

Prompts

  • `data-modeling`: Expert advice on MongoDB schema design for specific use cases

Other Features

  • Overview
  • New Database Metadata

Other Features: Overview

MongoDB Lens includes numerous other features:
  • [Config File](#configuration-config-file): Custom configuration via ~/.mongodb-lens.[jsonc|json]
  • [Env Var Overrides](#configuration-environment-variable-overrides): Override config settings via process.env.CONFIG_*
  • [Confirmation System](#data-protection-confirmation-for-destructive-operations): Two-step verification for destructive operations
  • [Multiple Connections](#configuration-multiple-mongodb-connections): Define and switch between named URI aliases
  • [Component Disabling](#disabling-tools): Selectively disable tools, prompts or resources
  • Connection Resilience: Auto-reconnection with exponential backoff
  • Query Safeguards: Configurable limits and performance protections
  • Error Handling: Comprehensive JSONRPC error codes and messages
  • Schema Inference: Efficient schema analysis with intelligent sampling
  • Credential Protection: Connection string password obfuscation in logs
  • Memory Management: Auto-monitoring and cleanup for large operations
  • Smart Caching: Optimized caching for schema, indexes, fields and collections
  • Backwards Compatible: Support both modern and legacy MongoDB versions

Other Features: New Database Metadata

MongoDB Lens inserts a metadata collection into each database it creates.
This metadata collection stores a single document containing contextual information serving as a permanent record of the database's origin while ensuring the new and otherwise empty database persists in MongoDB's storage system.
Once you've added your own collections to your new database, you can safely remove the metadata collection via the drop-collection tool:
  • "Drop the new database's metadata collection"<br> <sup> Uses drop-collection tool (with confirmation)</sup>

Installation

MongoDB Lens can be installed and run in several ways:
  • NPX (Easiest)
  • Docker Hub
  • Node.js from Source
  • Docker from Source
  • Installation Verification
  • Older MongoDB Versions

Installation: NPX

[!NOTE]<br> NPX requires Node.js installed and running on your system (suggestion: use Volta).
The easiest way to run MongoDB Lens is using NPX.
First, ensure Node.js is installed:
Then, run MongoDB Lens via NPX:
[!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 installed and running on your system.
First, ensure Docker is installed:
Then, run MongoDB Lens via Docker Hub:

Installation: Node.js from Source

[!NOTE]<br> Node.js from source requires Node.js installed and running on your system (suggestion: use Volta).
  1. Clone the MongoDB Lens repository:<br>
  1. Navigate to the cloned repository directory:<br>
  1. Ensure Node.js is installed:<br>
  1. Install Node.js dependencies:<br>
  1. Start the server:<br>

Installation: Docker from Source

[!NOTE]<br> Docker from source requires Docker installed and running on your system.
  1. Clone the MongoDB Lens repository:<br>
  1. Navigate to the cloned repository directory:<br>
  1. Ensure Docker is installed:<br>
  1. Build the Docker image:<br>
  1. Run the container:<br>

Installation Verification

To verify the installation, paste and run the following JSONRPC message into the server's stdio:
The server should respond with a list of databases in your MongoDB instance, for example:
MongoDB Lens is now installed and ready to accept MCP requests.

Installation: Older MongoDB Versions

If connecting to a MongoDB instance with a version < 4.0, the MongoDB Node.js driver used by the latest version of MongoDB Lens will not be compatible. Specifically, MongoDB Node.js driver versions 4.0.0 and above require MongoDB version 4.0 or higher.
To use MongoDB Lens with older MongoDB instances, you need to use a MongoDB Node.js driver version from the 3.x series (e.g. 3.7.4 which is compatible with MongoDB 3.6).

Older MongoDB Versions: Running from Source

  1. Clone the MongoDB Lens repository:<br>
  1. Navigate to the cloned repository directory:<br>
  1. Modify package.json:<br>
  1. Install Node.js dependencies:<br>
  1. Start MongoDB Lens:<br>
This will use the older driver version compatible with your MongoDB instance.
[!NOTE]<br> You may also need to revert this commit to add back useNewUrlParser and useUnifiedTopology MongoDB configuration options.

Older MongoDB Versions: Using NPX or Docker

If you prefer to use NPX or Docker, you'll need to use an older version of MongoDB Lens that was published with a compatible driver.
For example, MongoDB Lens 8.3.0 uses MongoDB Node.js driver 3.7.4 (see: `package-lock.json`).
To run an older version of MongoDB Lens using NPX, specify the version tag:
Similarly for Docker:

Configuration

  • MongoDB Connection String
  • Config File
  • Config File Generation
  • Multiple MongoDB Connections
  • Environment Variable Overrides
  • Cross-Platform Environment Variables

Configuration: MongoDB Connection String

The server accepts a MongoDB connection string as its only argument.
Example NPX usage:
MongoDB connection strings have the following format:
Example connection strings:
  • Local connection:<br> mongodb://localhost:27017
  • Connection to mydatabase with credentials from admin database:<br> mongodb://username:password@hostname:27017/mydatabase?authSource=admin
  • Connection to mydatabase with various other options:<br> mongodb://hostname:27017/mydatabase?retryWrites=true&w=majority
If no connection string is provided, the server will attempt to connect via local connection.

Configuration: Config File

MongoDB Lens supports extensive customization via JSON configuration file.
[!NOTE]<br> The config file is optional. MongoDB Lens will run with default settings if no config file is provided.
[!TIP]<br> You only need to include the settings you want to customize in the config file. MongoDB Lens will use default settings for any omitted values.
[!TIP]<br> MongoDB Lens supports both .json and .jsonc (JSON with comments) config file formats.
Note: Code block was split into 3 parts due to size limits.
By default, MongoDB Lens looks for the config file at:
  • ~/.mongodb-lens.jsonc first, then falls back to
  • ~/.mongodb-lens.json if the former doesn't exist
To customize the config file path, set the environment variable CONFIG_PATH to the desired file path.
Example NPX usage:
Example Docker Hub usage:

Configuration: Config File Generation

You can generate a configuration file automatically using the config:create script:
This script extracts the example configuration file above and saves it to: ~/.mongodb-lens.jsonc

Config File Generation: Custom Path

You can specify a custom output location using the CONFIG_PATH environment variable.
  • If CONFIG_PATH has no file extension, it's treated as a directory and .mongodb-lens.jsonc is appended
  • If CONFIG_PATH ends with .json (not .jsonc) comments are removed from the generated file
Example NPX usage:
Example Node.js usage:

Configuration: Multiple MongoDB Connections

MongoDB Lens supports multiple MongoDB URIs with aliases in your config file, allowing you to easily switch between different MongoDB instances using simple names.
To configure multiple connections, set the mongoUri config setting to an object with alias-URI pairs:
With this configuration:
  • The first URI in the list (e.g. main) becomes the default connection at startup
  • You can switch connections using natural language: "Connect to backup" or "Connect to atlas"
  • The original syntax still works: "Connect to mongodb://localhost:27018"
  • The list-connections tool shows all available connection aliases
[!NOTE]<br> When using the command-line argument to specify a connection, you can use either a full MongoDB URI or an alias defined in your configuration file.
[!TIP]<br> To add connection aliases at runtime, use the add-connection-alias tool.

Configuration: Environment Variable Overrides

MongoDB Lens supports environment variable overrides for configuration settings.
Environment variables take precedence over config file settings.
Config environment variables follow the naming pattern:
Example overrides:
[object Object]
[object Object]
[object Object]
[object Object]
[object Object]
[object Object]
[object Object]
[object Object]
[object Object]
[object Object]
[object Object]
[object Object]
[object Object]
[object Object]
[object Object]
[object Object]
For environment variable values:
  • For boolean settings, use string values 'true' or 'false'.
  • For numeric settings, use string representations.
  • For nested objects or arrays, use JSON strings.
Example NPX usage:
Example Docker Hub usage:

Configuration: Cross-Platform Environment Variables

For consistent environment variable usage across Windows, macOS, and Linux, consider using cross-env:
  1. Install cross-env globally:<br>
  1. Prefix any NPX or Node.js environment variables in this document's examples:<br>

Client Setup

  • Claude Desktop
  • MCP Inspector
  • Other MCP Clients

Client Setup: Claude Desktop

To use MongoDB Lens with Claude Desktop:
  1. Install Claude Desktop
  1. Open claude_desktop_config.json (create if it doesn't exist):
  1. Add the MongoDB Lens server configuration as per configuration options
  1. Restart Claude Desktop
  1. Start a conversation with Claude about your MongoDB data

Claude Desktop Configuration Options

  • Option 1: NPX (Recommended)
  • Option 2: Docker Hub Image
  • Option 3: Local Node.js Installation
  • Option 4: Local Docker Image
For each option:
  • Replace mongodb://your-connection-string with your MongoDB connection string or omit it to use the default mongodb://localhost:27017.
  • To use a custom config file, set `CONFIG_PATH` environment variable.
  • To include environment variables:
Option 1: NPX (Recommended)
Option 2: Docker Hub Image
Option 3: Local Node.js Installation
Option 4: Local Docker Image

Client Setup: MCP Inspector

MCP Inspector is a tool designed for testing and debugging MCP servers.
[!NOTE]<br> MCP Inspector starts a proxy server on port 3000 and web client on port 5173.
Example NPX usage:
  1. Run MCP Inspector:<br>
  1. Open MCP Inspector: http://localhost:5173
MCP Inspector should support the full range of MongoDB Lens capabilities, including autocompletion for collection names and query fields.
For more, see: MCP Inspector

Client Setup: Other MCP Clients

MongoDB Lens should be usable with any MCP-compatible client.

Data Protection

To protect your data while using MongoDB Lens, consider the following:
  • Read-Only User Accounts
  • Working with Database Backups
  • Data Flow Considerations
  • Confirmation for Destructive Operations
  • Disabling Destructive Operations

Data Protection: Read-Only User Accounts

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.
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:
Then, apply those credentials to your MongoDB connection string:
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.

Data Protection: Working with Database Backups

When working with MongoDB Lens, consider connecting to a backup copy of your data hosted on a separate MongoDB instance.
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).
This approach gives you a sandbox to test complex or destructive operations against without risking accidental corruption of your live data.

Data Protection: Data Flow Considerations

  • How Your Data Flows Through the System
  • Protecting Sensitive Data with Projection
  • Connection Aliases and Passwords
  • Local Setup for Maximum Safety

Data Flow Considerations: How Your Data Flows Through the System

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.
When you send a MongoDB related query through your MCP client, here s what happens:
[!NOTE]<br> While this example uses a local MongoDB instance, the same principles apply to remote MongoDB instances.
  1. You submit a request<br><sup> e.g. "Show me all users older than 30"</sup>
  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>
  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>
  1. The client asks MongoDB Lens to run the tool<br><sup> This occurs locally on your machine via stdio.</sup>
  1. MongoDB Lens queries your MongoDB database
  1. MongoDB Lens retrieves your MongoDB query results
  1. MongoDB Lens sends the data back to the client<br><sup> The client receives results formatted by MongoDB Lens.</sup>
  1. The client forwards the data to the remote LLM<br><sup> The LLM provider sees the exact data returned by MongoDB Lens.</sup>
  1. The remote LLM processes the data<br><sup> It may summarize or format the results further.</sup>
  1. The remote LLM sends the final response to the client<br><sup> The client displays the answer to you.</sup>
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.

Data Flow Considerations: Protecting Sensitive Data with Projection

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.
Example projection usage:
  • "Show me all users older than 30, but use projection to hide their passwords."<br> <sup> Uses find-documents tool with projection</sup>

Data Flow Considerations: Connection Aliases and Passwords

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, where they remain local and are not transmitted to the LLM.

Data Flow Considerations: Local Setup for Maximum Safety

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.

Data Protection: Confirmation for Destructive Operations

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:
  1. First tool invocation: Returns a 4-digit confirmation token that expires after 5 minutes
  1. Second tool invocation: Executes the operation if provided with the valid token
For an example of the confirmation process, see: Working with Confirmation Protection
Tools that require confirmation include:
  • drop-user: Remove a database user
  • drop-index: Remove an index (potential performance impact)
  • drop-database: Permanently delete a database
  • drop-collection: Delete a collection and all its documents
  • delete-document: Delete one or multiple documents
  • bulk-operations: When including delete operations
  • rename-collection: When the target collection exists and will be dropped
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.
[!NOTE]<br> If you're working in a controlled environment where data loss is acceptable, you can configure MongoDB Lens to bypass confirmation and perform destructive operations immediately.

Bypassing Confirmation for Destructive Operations

You might want to bypass the token confirmation system.
Set the environment variable CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS to true to execute destructive operations immediately without confirmation:
[!WARNING]<br> 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.

Data Protection: Disabling Destructive Operations

  • Disabling Tools
  • High-Risk Tools
  • Medium-Risk Tools