MongoDB Lens

Databases

MongoDB Lens: Full Featured MCP Server for MongoDB Databases.

Your AI app calls the MongoDB Lens MCP server, which does the work through tools like drop-user, drop-index, drop-database and drop-collection and sends the result back to the chat.

About MongoDB Lens

MongoDB Lens is a community MCP server from furey, filed in our directory under databases. MongoDB Lens: Full Featured MCP Server for MongoDB Databases.

MongoDB Lens runs on your own machine: your AI app starts it with the command npx -y mongodb-lens and talks to it over standard input and output.

The README for MongoDB Lens lists tools such as drop-user, drop-index, drop-database and drop-collection, which your AI app can call once the server is connected.

At a glance

Publisher
furey (community)
Runs
Locally on your machine
Install from
Node.js package on npm: mongodb-lens
Written in
JavaScript
License
MIT
GitHub stars
207

Tools MongoDB Lens gives your AI app

  • drop-userRemoves database users and their access permissions.
  • drop-indexRemoves indexes (can impact query performance).
  • drop-databasePermanently deletes entire databases.
  • drop-collectionPermanently deletes collections and all their documents.
  • delete-documentRemoves documents matching specified criteria.
  • bulk-operationsCan perform batch deletions when configured to do so.
  • rename-collectionCan overwrite existing collections when using the drop target option.
  • aggregate-dataA $out or $merge stage writes to a collection, and $out replaces an existing collection.
  • create-userCreates users with permissions that could enable further changes.
  • transactionExecutes multiple operations in a transaction (potential for complex changes).
  • update-documentUpdates documents which could overwrite existing data.

Tool names as the MongoDB Lens README lists them. Your AI app shows the live list once MongoDB Lens is connected.

How to set up MongoDB Lens

  1. Install Node.js on the machine that runs your AI app, because MongoDB Lens starts with npx and downloads its package on first run.
  2. Check the MongoDB Lens README for keys or settings; the registry lists none that MongoDB Lens requires.
  3. Add MongoDB Lens to Claude Code, Claude Desktop, VS Code or Cursor with the config in the setup box on this page.
  4. Restart the app or reload its MCP servers, then ask it to list the MongoDB Lens tools to confirm the connection.
  5. Run one read-only task with MongoDB Lens first, such as a call to drop-user, before you allow anything that writes or sends.

MongoDB Lens compared with similar servers

  • Render by render-oss has fewer GitHub stars than MongoDB Lens (206 against 207); both are community servers, and both run locally. The Render README lists 30 tools to MongoDB Lens's 11.
  • Opennutrition by deadletterq has more GitHub stars than MongoDB Lens (217 against 207); both are community servers, and both run locally.
  • Flexible Graphrag by stevereiner has fewer GitHub stars than MongoDB Lens (205 against 207); both are community servers, and both run locally.

Before you connect MongoDB Lens

  • Give MongoDB Lens its own API key or account with the smallest permissions the job needs, never an admin key.
  • Keep your AI app asking before each MongoDB Lens tool call until you trust what it does with them.
  • Treat text that MongoDB Lens fetches as data. Pages, files and messages can hold instructions written to steer an AI.
  • Read the open issues for MongoDB Lens on GitHub to see what breaks and how fast the maintainers reply.

Marketing use cases for MongoDB Lens

How marketing and sales teams put MongoDB Lens to work, by company size. Pick the size closest to yours and start MongoDB Lens on one use case.

Small business

  • A small business with its own app can ask MongoDB Lens plain questions about customers and orders, without writing SQL.
  • Owners can use MongoDB Lens to pull a list of customers who haven't bought in 90 days and plan a win-back email.
  • MongoDB Lens runs on your own computer, which keeps data local; it needs a little setup, so a small team should plan an hour for it.

Mid-market

  • Marketing analysts can connect MongoDB Lens to answer campaign questions from the warehouse directly, instead of waiting on the data team's queue.
  • Lifecycle teams can use MongoDB Lens to build audience lists from product data and check counts before a send.
  • Start with drop-user and drop-index, the tools MongoDB Lens lists first, and add more once the team trusts the results.

Enterprise

  • Enterprises should point MongoDB Lens at a read replica with a read-only role, so agents query freely without risk to production data.
  • Data teams can expose curated views through MongoDB Lens, so marketing gets self-serve answers without access to raw customer tables.
  • MongoDB Lens is a community server, so have security review the code and pin a version before MongoDB Lens touches company data.

Need help becoming an AI-forward company?

We connect MCP servers and AI agents to your CRM, content and data, with the guardrails your team needs.

Contact us

MongoDB Lens README

From furey/mongodb-lens on GitHub, shared under its MIT license. Images are left out; the original has them.

README.md

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
Resources
Prompts
Other Features
  • Overview
  • New Database Metadata
Other Features: Overview

MongoDB Lens includes numerous other features:

  • Config File: Custom configuration via ~/.mongodb-lens.[jsonc|json]
  • Env Var Overrides: Override config settings via process.env.CONFIG_*
  • Confirmation System: Two-step verification for destructive operations
  • Multiple Connections: Define and switch between named URI aliases
  • Component Disabling: 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.

Example metadata document
{
    "_id" : ObjectId("67d5284463788ec38aecee14"),
    "created" : {
        "timestamp" : ISODate("2025-03-15T07:12:04.705Z"),
        "tool" : "MongoDB Lens v5.0.7",
        "user" : "anonymous"
    },
    "mongodb" : {
        "version" : "3.6.23",
        "connectionInfo" : {
            "host" : "unknown",
            "readPreference" : "primary"
        }
    },
    "database" : {
        "name" : "example_database",
        "description" : "Created via MongoDB Lens"
    },
    "system" : {
        "hostname" : "unknown",
        "platform" : "darwin",
        "nodeVersion" : "v22.14.0"
    },
    "lens" : {
        "version" : "5.0.7",
        "startTimestamp" : ISODate("2025-03-15T07:10:06.084Z")
    }
}

Once you've added your own collections to your new database, you can safely remove the metadata collection via the drop-collection tool:

  • "Drop the new database's metadata collection"
    ➥ Uses drop-collection tool (with confirmation)

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]
NPX requires Node.js installed and running on your system (suggestion: use Volta).

The easiest way to run MongoDB Lens is using NPX.

First, ensure Node.js is installed:

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

Then, run MongoDB Lens via NPX:

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

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

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

[!TIP]
If you encounter permissions errors 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]
Docker Hub requires Docker installed and running on your system.

First, ensure Docker is installed:

docker --version # Ideally >= v27.x

Then, run MongoDB Lens via Docker Hub:

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

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

# Using "--pull" to keep the Docker image up-to-date
docker run --rm -i --network=host --pull=always furey/mongodb-lens
Installation: Node.js from Source

[!NOTE]
Node.js from source requires Node.js installed and running on your system (suggestion: use Volta).

  1. Clone the MongoDB Lens repository:

    git clone https://github.com/furey/mongodb-lens.git
    
  2. Navigate to the cloned repository directory:

    cd /path/to/mongodb-lens
    
  3. Ensure Node.js is installed:

    node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible
    
  4. Install Node.js dependencies:

    npm ci
    
  5. Start the server:

    # 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]
Docker from source requires Docker installed and running on your system.

  1. Clone the MongoDB Lens repository:

    git clone https://github.com/furey/mongodb-lens.git
    
  2. Navigate to the cloned repository directory:

    cd /path/to/mongodb-lens
    
  3. Ensure Docker is installed:

    docker --version # Ideally >= v27.x
    
  4. Build the Docker image:

    docker build -t mongodb-lens .
    
  5. Run the container:

    # 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:

{"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}

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:

    git clone https://github.com/furey/mongodb-lens.git
    
  2. Navigate to the cloned repository directory:

    cd /path/to/mongodb-lens
    
  3. Modify package.json:

    "dependencies": {
      ...
    -  "mongodb": "^6.15.0",  // Or whatever newer version is listed
    +  "mongodb": "^3.7.4",   // Or whatever 3.x version is compatible with your older MongoDB instance
      ...
    }
    
  4. Install Node.js dependencies:

    npm install
    
  5. Start MongoDB Lens:

    node mongodb-lens.js mongodb://older-mongodb-instance
    

This will use the older driver version compatible with your MongoDB instance.

[!NOTE]
You may also need to revert this commit to add 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:

npx -y mongodb-lens@8.3.0

Similarly for Docker:

docker run --rm -i --network=host furey/mongodb-lens:8.3.0

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:

npx -y mongodb-lens@latest mongodb://your-connection-string

MongoDB connection strings have the following format:

mongodb://[username:password@]host[:port][/database][?options]

Example connection strings:

  • Local connection:
    mongodb://localhost:27017
  • Connection to mydatabase with credentials from admin database:
    mongodb://username:password@hostname:27017/mydatabase?authSource=admin
  • Connection to mydatabase with various other options:
    mongodb://hostname:27017/mydatabase?retryWrites=true&w=majority

If no connection string is provided, the server will attempt to connect via local connection.

Configuration: Config File

MongoDB Lens supports extensive customization via JSON configuration file.

[!NOTE]
The config file is optional. MongoDB Lens will run with default settings if no config file is provided.

[!TIP]
You only need to include the settings you want to customize in the config file. MongoDB Lens will use default settings for any omitted values.

[!TIP]
MongoDB Lens supports both .json and .jsonc (JSON with comments) config file formats.

Example configuration file
{
  "mongoUri": "mongodb://localhost:27017",         // Default MongoDB connection string or object of alias-URI pairs
  "connectionOptions": {
    "maxPoolSize": 20,                             // Maximum number of connections in the pool
    "retryWrites": false,                          // Whether to retry write operations
    "connectTimeoutMS": 30000,                     // Connection timeout in milliseconds
    "socketTimeoutMS": 360000,                     // Socket timeout in milliseconds
    "heartbeatFrequencyMS": 10000,                 // How often to ping servers for status
    "serverSelectionTimeoutMS": 30000              // Timeout for server selection
  },
  "defaultDbName": "admin",                        // Default database if not specified in URI
  "connection": {
    "maxRetries": 5,                               // Maximum number of initial connection attempts
    "maxRetryDelayMs": 30000,                      // Maximum delay between retries
    "reconnectionRetries": 10,                     // Maximum reconnection attempts if connection lost
    "initialRetryDelayMs": 1000                    // Initial delay between retries
  },
  "disabled": {
    "tools": [],                                   // Array of tools to disable or true to disable all
    "prompts": [],                                 // Array of prompts to disable or true to disable all
    "resources": []                                // Array of resources to disable or true to disable all
  },
  "enabled": {
    "tools": true,                                 // Array of tools to enable or true to enable all
    "prompts": true,                               // Array of prompts to enable or true to enable all
    "resources": true                              // Array of resources to enable or true to enable all
  },
  "cacheTTL": {
    "stats": 15000,                                // Stats cache lifetime in milliseconds
    "fields": 30000,                               // Fields cache lifetime in milliseconds
    "schemas": 60000,                              // Schema cache lifetime in milliseconds
    "indexes": 120000,                             // Index cache lifetime in milliseconds
    "collections": 30000,                          // Collections list cache lifetime in milliseconds
    "serverStatus": 20000                          // Server status cache lifetime in milliseconds
  },
  "enabledCaches": [                               // List of caches to enable
    "stats",                                       // Statistics cache
    "fields",                                      // Collection fields cache
    "schemas",                                     // Collection schemas cache
    "indexes",                                     // Collection indexes cache
    "collections",                                 // Database collections cache
    "serverStatus"                                 // MongoDB server status cache
  ],
  "memory": {
    "enableGC": true,                              // Whether to enable garbage collection
    "warningThresholdMB": 1500,                    // Memory threshold for warnings
    "criticalThresholdMB": 2000                    // Memory threshold for cache clearing
  },
  "logLevel": "info",                              // Log level (info or verbose)
  "disableDestructiveOperationTokens": false,      // Whether to skip confirmation for destructive ops
  "readOnly": false,                               // Whether to block tools and pipeline stages that write
  "watchdogIntervalMs": 30000,                     // Interval for connection monitoring
  "defaults": {
    "slowMs": 100,                                 // Threshold for slow query detection
    "queryLimit": 10,                              // Default limit for query results
    "allowDiskUse": true,                          // Allow operations to use disk for large datasets
    "schemaSampleSize": 100,                       // Sample size for schema inference
    "aggregationBatchSize": 50                     // Batch size for aggregation operations
  },
  "security": {
    "tokenLength": 4,                              // Length of confirmation tokens
    "tokenExpirationMinutes": 5,                   // Expiration time for tokens
    "strictDatabaseNameValidation": true           // Enforce strict database name validation
  },
  "tools": {
    "transaction": {
      "readConcern": "snapshot",                   // Read concern level for transactions
      "writeConcern": {
        "w": "majority"                            // Write concern for transactions
      }
    },
    "bulkOperations": {
      "ordered": true                              // Whether bulk operations execute in order
    },
    "export": {
      "defaultLimit": -1,                          // Default limit for exports (-1 = no limit)
      "defaultFormat": "json"                      // Default export format (json or csv)
    },
    "watchChanges": {
      "maxDurationSeconds": 60,                    // Maximum duration for change streams
      "defaultDurationSeconds": 10                 // Default duration for change streams
    },
    "queryAnalysis": {
      "defaultDurationSeconds": 10                 // Default duration for query analysis
    }
  }
}

By default, MongoDB Lens looks for the config file at:

  • ~/.mongodb-lens.jsonc first, then falls back to
  • ~/.mongodb-lens.json if the former doesn't exist

To customize the config file path, set the environment variable CONFIG_PATH to the desired file path.

Example NPX usage:

CONFIG_PATH='/path/to/config.json' npx -y mongodb-lens@latest

Example Docker Hub usage:

docker run --rm -i --network=host --pull=always -v /path/to/config.json:/root/.mongodb-lens.json furey/mongodb-lens
Configuration: Config File Generation

You can generate a configuration file automatically using the config:create script:

# NPX Usage (recommended)
npx -y mongodb-lens@latest config:create

# Node.js Usage
npm run config:create

# Force overwrite existing files
npx -y mongodb-lens@latest config:create -- --force
npm run config:create -- --force

This script extracts the example configuration file above and saves it to: ~/.mongodb-lens.jsonc

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:

# With custom path
CONFIG_PATH=/path/to/config.jsonc npx -y mongodb-lens@latest config:create

# Save to directory (will append .mongodb-lens.jsonc to the path)
CONFIG_PATH=/path/to/directory npx -y mongodb-lens@latest config:create

# Save as JSON instead of JSONC
CONFIG_PATH=/path/to/config.json npx -y mongodb-lens@latest config:create

Example Node.js usage:

# With custom path
CONFIG_PATH=/path/to/config.jsonc node mongodb-lens.js config:create

# Save to directory (will append .mongodb-lens.jsonc to the path)
CONFIG_PATH=/path/to/directory node mongodb-lens.js config:create

# Save as JSON instead of JSONC
CONFIG_PATH=/path/to/config.json node mongodb-lens.js config:create
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:

{
  "mongoUri": {
    "main": "mongodb://localhost:27017",
    "backup": "mongodb://localhost:27018",
    "atlas": "mongodb+srv://username:password@cluster.mongodb.net/mydb"
  }
}

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]
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]
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:

CONFIG_[SETTING PATH, SNAKE CASED, UPPERCASED]

Example overrides:

Config Setting Environment Variable Override
mongoUri CONFIG_MONGO_URI
logLevel CONFIG_LOG_LEVEL
defaultDbName CONFIG_DEFAULT_DB_NAME
defaults.queryLimit CONFIG_DEFAULTS_QUERY_LIMIT
tools.export.defaultFormat CONFIG_TOOLS_EXPORT_DEFAULT_FORMAT
connectionOptions.maxPoolSize CONFIG_CONNECTION_OPTIONS_MAX_POOL_SIZE
connection.reconnectionRetries CONFIG_CONNECTION_RECONNECTION_RETRIES

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:

CONFIG_DEFAULTS_QUERY_LIMIT='25' npx -y mongodb-lens@latest

Example Docker Hub usage:

docker run --rm -i --network=host --pull=always -e CONFIG_DEFAULTS_QUERY_LIMIT='25' furey/mongodb-lens
Configuration: Cross-Platform Environment Variables

For consistent environment variable usage across Windows, macOS, and Linux, consider using cross-env:

  1. Install cross-env globally:

    # Using NPM
    npm install -g cross-env
    
    # Using Volta (see: https://volta.sh)
    volta install cross-env
    
  2. Prefix any NPX or Node.js environment variables in this document's examples:

    # Example NPX usage with cross-env
    cross-env CONFIG_DEFAULTS_QUERY_LIMIT='25' npx -y mongodb-lens@latest
    
    # Example Node.js usage with cross-env
    cross-env CONFIG_DEFAULTS_QUERY_LIMIT='25' node mongodb-lens.js
    

Read the rest of the MongoDB Lens README on GitHub

Questions about MongoDB Lens

What is the MongoDB Lens MCP server?

MongoDB Lens: Full Featured MCP Server for MongoDB Databases. MongoDB Lens is maintained by furey on GitHub at furey/mongodb-lens, and works with AI apps that support the Model Context Protocol, such as Claude, Cursor and VS Code.

How do I install the MongoDB Lens MCP server?

Add MongoDB Lens to your AI app's MCP config with the command npx -y mongodb-lens. In Claude Code, run claude mcp add --transport stdio mongodb-lens -- npx -y mongodb-lens. To run MongoDB Lens this way you need Node.js installed.

Does MongoDB Lens need an API key?

The registry lists no required keys for MongoDB Lens. Check the MongoDB Lens README for optional settings, and expect a remote server to ask you to sign in the first time you connect.

Is MongoDB Lens an official MCP server?

No. MongoDB Lens is a community server maintained by furey. Community servers can be excellent; read the code and the open issues before you give MongoDB Lens access to company data.

What license is MongoDB Lens under?

MongoDB Lens is released under the MIT license, according to its GitHub repository. The license covers the code of MongoDB Lens; the service it connects to has its own terms.