MCP Now
MongoDB Lens

MongoDB Lens

by furey
GitHub

Full Featured MCP Server for MongoDB Databases.

mongodb
database
collection
connection
data

MongoDB Lens

License Docker Hub Version NPM Version Buy Me a Coffee

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

Tools

Resources

Prompts

Other Features

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
1{ 2 "_id" : ObjectId("67d5284463788ec38aecee14"), 3 "created" : { 4 "timestamp" : ISODate("2025-03-15T07:12:04.705Z"), 5 "tool" : "MongoDB Lens v5.0.7", 6 "user" : "anonymous" 7 }, 8 "mongodb" : { 9 "version" : "3.6.23", 10 "connectionInfo" : { 11 "host" : "unknown", 12 "readPreference" : "primary" 13 } 14 }, 15 "database" : { 16 "name" : "example_database", 17 "description" : "Created via MongoDB Lens" 18 }, 19 "system" : { 20 "hostname" : "unknown", 21 "platform" : "darwin", 22 "nodeVersion" : "v22.14.0" 23 }, 24 "lens" : { 25 "version" : "5.0.7", 26 "startTimestamp" : ISODate("2025-03-15T07:10:06.084Z") 27 } 28}

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:

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:

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

Then, run MongoDB Lens via NPX:

1# Using default connection string mongodb://localhost:27017 2npx -y mongodb-lens 3 4# Using custom connection string 5npx -y mongodb-lens mongodb://your-connection-string 6 7# Using "@latest" to keep the package up-to-date 8npx -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:

1docker --version # Ideally >= v27.x

Then, run MongoDB Lens via Docker Hub:

1# Using default connection string mongodb://localhost:27017 2docker run --rm -i --network=host furey/mongodb-lens 3 4# Using custom connection string 5docker run --rm -i --network=host furey/mongodb-lens mongodb://your-connection-string 6 7# Using "--pull" to keep the Docker image up-to-date 8docker 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:
    1git clone https://github.com/furey/mongodb-lens.git
  2. Navigate to the cloned repository directory:
    1cd /path/to/mongodb-lens
  3. Ensure Node.js is installed:
    1node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible
  4. Install Node.js dependencies:
    1npm ci
  5. Start the server:
    1# Using default connection string mongodb://localhost:27017 2node mongodb-lens.js 3 4# Using custom connection string 5node 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:
    1git clone https://github.com/furey/mongodb-lens.git
  2. Navigate to the cloned repository directory:
    1cd /path/to/mongodb-lens
  3. Ensure Docker is installed:
    1docker --version # Ideally >= v27.x
  4. Build the Docker image:
    1docker build -t mongodb-lens .
  5. Run the container:
    1# Using default connection string mongodb://localhost:27017 2docker run --rm -i --network=host mongodb-lens 3 4# Using custom connection string 5docker 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:

1{"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:

1{"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.

Configuration

Configuration: MongoDB Connection String

The server accepts a MongoDB connection string as its only argument.

Example NPX usage:

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

MongoDB connection strings have the following format:

1mongodb://[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
1{ 2 "mongoUri": "mongodb://localhost:27017", // Default MongoDB connection string or object of alias-URI pairs 3 "connectionOptions": { 4 "maxPoolSize": 20, // Maximum number of connections in the pool 5 "retryWrites": false, // Whether to retry write operations 6 "useNewUrlParser": true, // Use MongoDB's new URL parser 7 "connectTimeoutMS": 30000, // Connection timeout in milliseconds 8 "socketTimeoutMS": 360000, // Socket timeout in milliseconds 9 "useUnifiedTopology": true, // Use the new unified topology engine 10 "heartbeatFrequencyMS": 10000, // How often to ping servers for status 11 "serverSelectionTimeoutMS": 30000 // Timeout for server selection 12 }, 13 "defaultDbName": "admin", // Default database if not specified in URI 14 "connection": { 15 "maxRetries": 5, // Maximum number of initial connection attempts 16 "maxRetryDelayMs": 30000, // Maximum delay between retries 17 "reconnectionRetries": 10, // Maximum reconnection attempts if connection lost 18 "initialRetryDelayMs": 1000 // Initial delay between retries 19 }, 20 "disabled": { 21 "tools": [], // List of tools to disable or true to disable all 22 "prompts": [], // List of prompts to disable or true to disable all 23 "resources": [] // List of resources to disable or true to disable all 24 }, 25 "cacheTTL": { 26 "stats": 15000, // Stats cache lifetime in milliseconds 27 "schemas": 60000, // Schema cache lifetime in milliseconds 28 "indexes": 120000, // Index cache lifetime in milliseconds 29 "collections": 30000, // Collections list cache lifetime in milliseconds 30 "serverStatus": 20000 // Server status cache lifetime in milliseconds 31 }, 32 "enabledCaches": [ // List of caches to enable 33 "stats", // Statistics cache 34 "fields", // Collection fields cache 35 "schemas", // Collection schemas cache 36 "indexes", // Collection indexes cache 37 "collections", // Database collections cache 38 "serverStatus" // MongoDB server status cache 39 ], 40 "memory": { 41 "enableGC": true, // Whether to enable garbage collection 42 "warningThresholdMB": 1500, // Memory threshold for warnings 43 "criticalThresholdMB": 2000 // Memory threshold for cache clearing 44 }, 45 "logLevel": "info", // Log level (info or verbose) 46 "disableDestructiveOperationTokens": false, // Whether to skip confirmation for destructive ops 47 "watchdogIntervalMs": 30000, // Interval for connection monitoring 48 "defaults": { 49 "slowMs": 100, // Threshold for slow query detection 50 "queryLimit": 10, // Default limit for query results 51 "allowDiskUse": true, // Allow operations to use disk for large datasets 52 "schemaSampleSize": 100, // Sample size for schema inference 53 "aggregationBatchSize": 50 // Batch size for aggregation operations 54 }, 55 "security": { 56 "tokenLength": 4, // Length of confirmation tokens 57 "tokenExpirationMinutes": 5, // Expiration time for tokens 58 "strictDatabaseNameValidation": true // Enforce strict database name validation 59 }, 60 "tools": { 61 "transaction": { 62 "readConcern": "snapshot", // Read concern level for transactions 63 "writeConcern": { 64 "w": "majority" // Write concern for transactions 65 } 66 }, 67 "bulkOperations": { 68 "ordered": true // Whether bulk operations execute in order 69 }, 70 "export": { 71 "defaultLimit": -1, // Default limit for exports (-1 = no limit) 72 "defaultFormat": "json" // Default export format (json or csv) 73 }, 74 "watchChanges": { 75 "maxDurationSeconds": 60, // Maximum duration for change streams 76 "defaultDurationSeconds": 10 // Default duration for change streams 77 }, 78 "queryAnalysis": { 79 "defaultDurationSeconds": 10 // Default duration for query analysis 80 } 81 } 82}

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:

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

Example Docker Hub usage:

1docker 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:

1# Create config file 2npm run config:create 3 4# Create config file (force overwrite existing) 5npm 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 configuration file output location using the CONFIG_PATH environment variable:

1# Save to a specific file path 2CONFIG_PATH=/path/to/config.jsonc npm run config:create 3 4# Save to a specific directory (will append .mongodb-lens.jsonc to the path) 5CONFIG_PATH=/path/to/directory npm run config:create 6 7# Save as JSON without comments 8CONFIG_PATH=/path/to/config.json npm run config:create

The script handles paths intelligently:

  • 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 automatically stripped from the output

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:

1{ 2 "mongoUri": { 3 "main": "mongodb://localhost:27017", 4 "backup": "mongodb://localhost:27018", 5 "atlas": "mongodb+srv://username:[email protected]/mydb" 6 } 7}

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:

1CONFIG_[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 | | connectionOptions.maxPoolSize | CONFIG_CONNECTION_OPTIONS_MAX_POOL_SIZE | | connection.reconnectionRetries | CONFIG_CONNECTION_RECONNECTION_RETRIES | | defaults.queryLimit | CONFIG_DEFAULTS_QUERY_LIMIT | | tools.export.defaultFormat | CONFIG_TOOLS_EXPORT_DEFAULT_FORMAT |

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:

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

Example Docker Hub usage:

1docker 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:
    1# Using NPM 2npm install -g cross-env 3 4# Using Volta (see: https://volta.sh) 5volta install cross-env
  2. Prefix any NPX or Node.js environment variables in this document's examples:
    1# Example NPX usage with cross-env 2cross-env CONFIG_DEFAULTS_QUERY_LIMIT='25' npx -y mongodb-lens@latest 3 4# Example Node.js usage with cross-env 5cross-env CONFIG_DEFAULTS_QUERY_LIMIT='25' node mongodb-lens.js

Client Setup

Client Setup: Claude Desktop

To use MongoDB Lens with Claude Desktop:

  1. Install Claude Desktop
  2. Open claude_desktop_config.json (create if it doesn't exist):
    • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
    • Windows: %APPDATA%\Claude\claude_desktop_config.json
  3. Add the MongoDB Lens server configuration as per configuration options
  4. Restart Claude Desktop
  5. Start a conversation with Claude about your MongoDB data

Claude Desktop Configuration Options

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:
    • For NPX or Node.js add "env": {} with key-value pairs, for example:
      1"command": "/path/to/npx", 2"args": [ 3 "-y", 4 "mongodb-lens@latest", 5 "mongodb://your-connection-string" 6], 7"env": { 8 "CONFIG_LOG_LEVEL": "verbose" 9}
    • For Docker add -e flags, for example:
      1"command": "docker", 2"args": [ 3 "run", "--rm", "-i", 4 "--network=host", 5 "--pull=always", 6 "-e", "CONFIG_LOG_LEVEL='verbose'", 7 "furey/mongodb-lens", 8 "mongodb://your-connection-string" 9]
Option 1: NPX (Recommended)
1{ 2 "mcpServers": { 3 "mongodb-lens": { 4 "command": "/path/to/npx", 5 "args": [ 6 "-y", 7 "mongodb-lens@latest", 8 "mongodb://your-connection-string" 9 ] 10 } 11 } 12}
Option 2: Docker Hub Image
1{ 2 "mcpServers": { 3 "mongodb-lens": { 4 "command": "docker", 5 "args": [ 6 "run", "--rm", "-i", 7 "--network=host", 8 "--pull=always", 9 "furey/mongodb-lens", 10 "mongodb://your-connection-string" 11 ] 12 } 13 } 14}
Option 3: Local Node.js Installation
1{ 2 "mcpServers": { 3 "mongodb-lens": { 4 "command": "/path/to/node", 5 "args": [ 6 "/path/to/mongodb-lens.js", 7 "mongodb://your-connection-string" 8 ] 9 } 10 } 11}
Option 4: Local Docker Image
1{ 2 "mcpServers": { 3 "mongodb-lens": { 4 "command": "docker", 5 "args": [ 6 "run", "--rm", "-i", 7 "--network=host", 8 "mongodb-lens", 9 "mongodb://your-connection-string" 10 ] 11 } 12 } 13}

Client Setup: MCP Inspector

MCP Inspector is a tool designed for testing and debugging MCP servers.

[!NOTE]
MCP Inspector starts a proxy server on port 3000 and web client on port 5173.

Example NPX usage:

  1. Run MCP Inspector:
    1# Using default connection string mongodb://localhost:27017 2npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest 3 4# Using custom connection string 5npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest mongodb://your-connection-string 6 7# Using custom ports 8SERVER_PORT=1234 CLIENT_PORT=5678 npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest
  2. 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.

For more, see: MCP Documentation: Example Clients

Data Protection

To protect your data while using MongoDB Lens, consider the following:

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:

1use admin 2 3db.createUser({ 4 user: 'readonly', 5 pwd: 'eXaMpLePaSsWoRd', 6 roles: [{ role: 'read', db: 'mydatabase' }] 7})

Then, apply those credentials to your MongoDB connection string:

1mongodb://readonly:eXaMpLePaSsWoRd@localhost:27017/mydatabase

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

1# Using NPX 2CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS=true npx -y mongodb-lens@latest 3 4# Using Docker 5docker run --rm -i --network=host --pull=always -e CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS='true' furey/mongodb-lens

[!WARNING]
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

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:

1{ 2 "disabled": { 3 "tools": [ 4 "drop-user", 5 "drop-index", 6 "drop-database", 7 "drop-collection", 8 "delete-document", 9 "bulk-operations", 10 "rename-collection" 11 ] 12 } 13}

High-Risk Tools

These tools can cause immediate data loss and should be considered for disabling in sensitive environments:

  • drop-user: Removes database users and their access permissions
  • drop-index: Removes indexes (can impact query performance)
  • drop-database: Permanently deletes entire databases
  • drop-collection: Permanently deletes collections and all their documents
  • delete-document: Removes documents matching specified criteria
  • bulk-operations: Can perform batch deletions when configured to do so
  • rename-collection: Can overwrite existing collections when using the drop target option

Medium-Risk Tools

These tools can modify data but typically don't cause immediate data loss:

  • create-user: Creates users with permissions that could enable further changes
  • transaction: Executes multiple operations in a transaction (potential for complex changes)
  • update-document: Updates documents which could overwrite existing data

Read-Only Configuration

For a complete read-only configuration, disable all potentially destructive tools:

1{ 2 "disabled": { 3 "tools": [ 4 "drop-user", 5 "drop-index", 6 "create-user", 7 "transaction", 8 "create-index", 9 "drop-database", 10 "drop-collection", 11 "insert-document", 12 "update-document", 13 "delete-document", 14 "bulk-operations", 15 "create-database", 16 "gridfs-operation", 17 "create-collection", 18 "rename-collection", 19 "create-timeseries" 20 ] 21 } 22}

This configuration allows MongoDB Lens to query and analyze data while preventing any modifications, providing multiple layers of protection against accidental data loss.

Tutorial

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:

  1. Start Sample Data Container
  2. Import Sample Data
  3. Connect MongoDB Lens
  4. Example Queries
  5. Working With Confirmation Protection

Tutorial: 1. Start Sample Data Container

[!NOTE]
This tutorial assumes you have Docker installed and running on your system.

[!IMPORTANT]
If Docker is already running a container on port 27017, stop it before proceeding.

  1. Initialise the sample data container:
    1docker run --name mongodb-sampledata -d -p 27017:27017 mongo:6
  2. Verify the container is running without issue:
    1docker ps | grep mongodb-sampledata

Tutorial: 2. Import Sample Data

MongoDB provides several sample datasets which we'll use to explore MongoDB Lens.

  1. Download the sample datasets:
    1curl -LO https://atlas-education.s3.amazonaws.com/sampledata.archive
  2. Copy the sample datasets into your sample data container:
    1docker cp sampledata.archive mongodb-sampledata:/tmp/
  3. Import the sample datasets into MongoDB:
    1docker exec -it mongodb-sampledata mongorestore --archive=/tmp/sampledata.archive

This will import several databases:

  • sample_airbnb: Airbnb listings and reviews
  • sample_analytics: Customer and account data
  • sample_geospatial: Geographic data
  • sample_mflix: Movie data
  • sample_restaurants: Restaurant data
  • sample_supplies: Supply chain data
  • sample_training: Training data for various applications
  • sample_weatherdata: Weather measurements

Tutorial: 3. Connect MongoDB Lens

Install MongoDB Lens as per the Quick Start instructions.

Set your MCP Client to connect to MongoDB Lens via: mongodb://localhost:27017

[!TIP]
Omitting the connection string from your MCP Client configuration will default the connection string to mongodb://localhost:27017.

Example Claude Desktop configuration:

1{ 2 "mcpServers": { 3 "mongodb-lens": { 4 "command": "/path/to/npx", 5 "args": [ 6 "-y", 7 "mongodb-lens@latest" 8 ] 9 } 10 } 11}

Tutorial: 4. Example Queries

With your MCP Client running and connected to MongoDB Lens, try the following example queries:

Example Queries: Basic Database Operations

  • "List all available databases"
    ➥ Uses list-databases tool
  • "What database am I currently using?"
    ➥ Uses current-database tool
  • "Switch to the sample_mflix database"
    ➥ Uses use-database tool
  • "Create a new database called test_db"
    ➥ Uses create-database tool
  • "Create another database called analytics_db and switch to it"
    ➥ Uses create-database tool with switch=true
  • "Drop the test_db database"
    ➥ Uses drop-database tool (with confirmation)

Example Queries: Collection Management

  • "What collections are in the current database?"
    ➥ Uses list-collections tool
  • "Create a new collection named user_logs"
    ➥ Uses create-collection tool
  • "Rename the user_logs collection to system_logs"
    ➥ Uses rename-collection tool
  • "Drop the system_logs collection"
    ➥ Uses drop-collection tool (with confirmation)
  • "Check the data consistency in the movies collection"
    ➥ Uses validate-collection tool

Example Queries: User Management

  • "Create a read-only user for analytics"
    ➥ Uses create-user tool
  • "Drop the inactive_user account"
    ➥ Uses drop-user tool (with confirmation)

Example Queries: Querying Data

  • "Count all documents in the movies collection"
    ➥ Uses count-documents tool
  • "Find the top 5 movies with the highest IMDB rating"
    ➥ Uses find-documents tool
  • "Show me aggregate data for movies grouped by decade"
    ➥ Uses aggregate-data tool
  • "List all unique countries where movies were produced"
    ➥ Uses distinct-values tool
  • "Search for movies containing 'godfather' in their title"
    ➥ Uses text-search tool
  • "Find German users with last name 'müller' using proper collation"
    ➥ Uses collation-query tool

Example Queries: Schema Analysis

  • "What's the schema structure of the movies collection?"
    ➥ Uses analyze-schema tool
  • "Compare the schema between users and comments collections"
    ➥ Uses compare-schemas tool
  • "Generate a JSON schema validator for the movies collection"
    ➥ Uses generate-schema-validator tool
  • "Analyze common query patterns for the movies collection"
    ➥ Uses analyze-query-patterns tool

Example Queries: Data Modification

  • "Insert a new movie document"
    ➥ Uses insert-document tool
  • "Update all movies from 1994 to add a 'classic' flag"
    ➥ Uses update-document tool
  • "Delete all movies with zero ratings"
    ➥ Uses delete-document tool (with confirmation)
  • "Run these bulk operations on the movies collection"
    ➥ Uses bulk-operations tool

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

Example Queries: Performance & Index Management

  • "Create an index on the title field in the movies collection"
    ➥ Uses create-index tool
  • "Drop the unused ratings_idx index"
    ➥ Uses drop-index tool (with confirmation)
  • "Explain the execution plan for finding movies from 1995"
    ➥ Uses explain-query tool
  • "Get statistics for the current database"
    ➥ Uses get-stats tool (database target)
  • "Show collection stats for the movies collection"
    ➥ Uses get-stats tool (collection target)

Example Queries: Geospatial & Special Operations

  • "Switch to sample_geospatial database, then find all shipwrecks within 10km of coordinates [-80.12, 26.46]"
    ➥ Uses geo-query tool
  • "Switch to sample_mflix database, then run this Map-Reduce to calculate movie counts by year with map 'function () { emit(this.year, 1) }' and reduce 'function (key, values) { return Array.sum(values) }'"
    ➥ Uses map-reduce tool
  • "Switch to sample_analytics database, then execute a transaction to move funds between accounts"
    ➥ Uses transaction tool
  • "Create a time series collection for sensor readings"
    ➥ Uses create-timeseries tool
  • "Watch for changes in the users collection for 30 seconds"
    ➥ Uses watch-changes tool
  • "List all files in the images GridFS bucket"
    ➥ Uses gridfs-operation tool (list operation)

Example Queries: Export, Administrative & Other Features

  • "Switch to sample_mflix database, then export the top 20 movies based on 'tomatoes.critic.rating' as a CSV with title, year and rating fields, output as raw csv text in a single code block"
    ➥ Uses export-data tool
  • "Switch to sample_analytics database, then check its sharding status"
    ➥ Uses shard-status tool
  • "Switch to sample_weatherdata database, and generate an interactive report on its current state"
    ➥ Uses numerous tools

Example Queries: Connection Management

  • "Connect to a different MongoDB server at mongodb://localhost:27018"
    ➥ Uses connect-mongodb tool
  • "Connect to MongoDB Atlas instance at mongodb+srv://username:[email protected]/mydb"
    ➥ Uses connect-mongodb tool
  • "Connect back to the original MongoDB server"
    ➥ Uses connect-original tool
  • "Connect to a MongoDB replica set without validating the connection"
    ➥ Uses connect-mongodb tool with validateConnection=false
  • "Add a new connection alias named prod for mongodb://username:password@prod-server:27017/mydb"
    ➥ Uses add-connection-alias tool

Tutorial: 5. Working With Confirmation Protection

MongoDB Lens includes a safety mechanism for potentially destructive operations. Here's how it works in practice:

  1. Request to drop a collection:
    "Drop the collection named test_collection"
    
  2. MongoDB Lens responds with a warning and confirmation token:
    ⚠️ DESTRUCTIVE OPERATION WARNING ⚠️
    
    You've requested to drop the collection 'test_collection'.
    
    This operation is irreversible and will permanently delete all data in this collection.
    
    To confirm, you must type the 4-digit confirmation code EXACTLY as shown below:
    
    Confirmation code: 9876
    
    This code will expire in 5 minutes for security purposes.
    
  3. Confirm the operation by submitting the confirmation token:
    "9876"
    
  4. MongoDB Lens executes the operation:
    Collection 'test_collection' has been permanently deleted.
    

This two-step process prevents accidental data loss by requiring explicit confirmation.

[!NOTE]
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.

Disclaimer

MongoDB Lens:

  • is licensed under the MIT License.
  • is not affiliated with or endorsed by MongoDB, Inc.
  • is written with the assistance of AI and may contain errors.
  • is intended for educational and experimental purposes only.
  • is provided as-is with no warranty—please use at your own risk.

Support

If you've found MongoDB Lens helpful consider supporting my work through:

Buy Me a Coffee | GitHub Sponsorship

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.