MongoDB Lens

by furey

87 574 downloads Not rated yet MIT

About

Integrates with MongoDB databases to enable browsing collections, executing queries, running aggregation pipelines, analyzing schemas, and optimizing performance through specialized database exploration tools.

Details

Repository
furey/mongodb-lens
License
MIT

Explore

Setting up with Highlight

This MCP is not yet compatible with Highlight’s one-click setup. However, you can still use it with Highlight by following these steps:

  1. Download and install Highlight from highlightai.com/download
  2. Navigate to the plugins tab and select "Add Custom Plugin"
  3. Configure the plugin with the settings below
    Plugin Name MongoDB Lens
    Command (node, npx, python, etc.) /path/to/npx
    Arguments
    • Argument 1 -y
    • Argument 2 mongodb-lens@latest
    • Argument 3 mongodb://your-connection-string

    Please refer to the README for specific instructions on how to obtain API keys or other required environment variables.

  4. Enable "Start Automatically" if you want the plugin to start when Highlight launches

From the repository

- Clone the MongoDB Lens repository:

git clone https://github.com/furey/mongodb-lens.git
"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 ... }
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 revertthis committo add backuseNewUrlParseranduseUnifiedTopologyMongoDB configuration options.

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

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

MongoDB connection strings have the following format:

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

- Local connection:
mongodb://localhost:27017
- Connection tomydatabasewith credentials fromadmindatabase:
mongodb://username:password@hostname:27017/mydatabase?authSource=admin
- Connection tomydatabasewith 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.

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.jsonand.jsonc(JSON with comments) config file formats.

{ "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 "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.jsoncfirst, then falls back to
- ~/.mongodb-lens.jsonif the former doesn't exist

To customize the config file path, set the environment variableCONFIG_PATHto the desired file path.

CONFIG_PATH='/path/to/config.json' npx -y mongodb-lens@latest
docker run --rm -i --network=host --pull=always -v /path/to/config.json:/root/.mongodb-lens.json furey/mongodb-lens

You can generate a configuration file automatically using theconfig:createscript:

# 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 theexample configuration fileabove and saves it to:~/.mongodb-lens.jsonc

You can specify a custom output location using theCONFIG_PATHenvironment variable.

- IfCONFIG_PATHhas no file extension, it's treated as a directory and.mongodb-lens.jsoncis appended
- IfCONFIG_PATHends with.json(not.jsonc) comments are removed from the generated file

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

MongoDB Lens supports multiple MongoDB URIs with aliases in yourconfig file, allowing you to easily switch between different MongoDB instances using simple names.

To configure multiple connections, set themongoUriconfig setting to an object with alias-URI pairs:

{ "mongoUri": { "main": "mongodb://localhost:27017", "backup": "mongodb://localhost:27018", "atlas": "mongodb+srv://username:[email protected]/mydb" } }

- 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"
- Thelist-connectionstool 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 theadd-connection-aliastool.

add-connection-alias

Add a new MongoDB connection alias.

aggregate-data

Execute aggregation pipelines.

analyze-query-patterns

Analyze live queries and suggest optimizations.

analyze-schema

Automatically infer collection schemas.

bulk-operations

Perform multiple operations efficiently (requires confirmation for destructive operations).

clear-cache

Clear memory caches to ensure fresh data.

collation-query

Find documents with language-specific collation rules.

compare-schemas

Compare schemas between two collections.

connect-mongodb

Connect to a different MongoDB URI.

connect-original

Connect back to the original MongoDB URI used at startup.

count-documents

Count documents matching specified criteria.

create-collection

Create new collections with custom options.

create-database

Create a new database with option to switch to it.

create-index

Create new indexes for performance optimization.

create-timeseries

Create time series collections for temporal data.

create-user

Create new database users with specific roles.

current-database

Show the current database context.

delete-document

Delete documents matching specified criteria (requires confirmation).

distinct-values

Extract unique values for any field.

drop-collection

Remove collections from the database (requires confirmation).

drop-database

Drop a database (requires confirmation).

drop-index

Remove indexes from collections (requires confirmation).

drop-user

Remove database users (requires confirmation).

explain-query

Analyze query execution plans.

export-data

Export query results in JSON or CSV format.

find-documents

Run queries with filters, projections, and sorting.

generate-schema-validator

Generate JSON Schema validators.

geo-query

Perform geospatial queries with various operators.

get-stats

Retrieve database or collection statistics.

gridfs-operation

Manage large files with GridFS buckets.

insert-document

Insert one or more documents into collections.

list-collections

Explore collections in the current database.

list-connections

View all available MongoDB connection aliases.

list-databases

View all accessible databases.

rename-collection

Rename existing collections (requires confirmation when dropping targets).

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.

update-document

Update documents matching specified criteria.

use-database

Switch to a specific database context.

validate-collection

Check for data inconsistencies.

watch-changes

Monitor real-time changes to collections.

- add-connection-alias: Add a new MongoDB connection alias
- aggregate-data: Execute aggregation pipelines
- analyze-query-patterns: Analyze live queries and suggest optimizations
- analyze-schema: Automatically infer collection schemas
- bulk-operations: Perform multiple operations efficiently (requires confirmation for destructive operations)
- clear-cache: Clear memory caches to ensure fresh data
- collation-query: Find documents with language-specific collation rules
- compare-schemas: Compare schemas between two collections
- connect-mongodb: Connect to a different MongoDB URI
- connect-original: Connect back to the original MongoDB URI used at startup
- count-documents: Count documents matching specified criteria
- create-collection: Create new collections with custom options
- create-database: Create a new database with option to switch to it
- create-index: Create new indexes for performance optimization
- create-timeseries: Create time series collections for temporal data
- create-user: Create new database users with specific roles
- current-database: Show the current database context
- delete-document: Delete documents matching specified criteria (requires confirmation)
- distinct-values: Extract unique values for any field
- drop-collection: Remove collections from the database (requires confirmation)
- drop-database: Drop a database (requires confirmation)
- drop-index: Remove indexes from collections (requires confirmation)
- drop-user: Remove database users (requires confirmation)
- explain-query: Analyze query execution plans
- export-data: Export query results in JSON or CSV format
- find-documents: Run queries with filters, projections, and sorting
- generate-schema-validator: Generate JSON Schema validators
- geo-query: Perform geospatial queries with various operators
- get-stats: Retrieve database or collection statistics
- gridfs-operation: Manage large files with GridFS buckets
- insert-document: Insert one or more documents into collections
- list-collections: Explore collections in the current database
- list-connections: View all available MongoDB connection aliases
- list-databases: View all accessible databases
- rename-collection: Rename existing collections (requires confirmation when dropping targets)
- 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
- update-document: Update documents matching specified criteria
- use-database: Switch to a specific database context
- validate-collection: Check for data inconsistencies
- watch-changes: Monitor real-time changes to collections

Claude Desktop / Cursor

Paste into your MCP client config file to install this server.

{
    "mcpServers": {
        "mongodb lens": {
            "env": {},
            "args": [
                "-y",
                "mongodb-lens@latest",
                "mongodb://your-connection-string"
            ],
            "command": "/path/to/npx"
        }
    }
}

Linux

{
    "env": [],
    "args": [
        "-y",
        "mongodb-lens@latest",
        "mongodb://your-connection-string"
    ],
    "command": "/path/to/npx"
}

Macos

{
    "env": [],
    "args": [
        "-y",
        "mongodb-lens@latest",
        "mongodb://your-connection-string"
    ],
    "command": "/path/to/npx"
}

Windows

{
    "env": [],
    "args": [
        "/c",
        "npx",
        "-y",
        "mongodb-lens@latest",
        "mongodb://your-connection-string"
    ],
    "command": "cmd"
}

MongoDB Lensis 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.

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

- InstallMongoDB Lens
-
ConfigureMongoDB Lens
-
Set upyour MCP Client (e.g.Claude Desktop,Cursor, etc)
- Explore your MongoDB databases with
natural language queries

- add-connection-alias: Add a new MongoDB connection alias
-
aggregate-data: Execute aggregation pipelines
-
analyze-query-patterns: Analyze live queries and suggest optimizations
-
analyze-schema: Automatically infer collection schemas
-
bulk-operations: Perform multiple operations efficiently (requires confirmationfor destructive operations)
-
clear-cache: Clear memory caches to ensure fresh data
-
collation-query: Find documents with language-specific collation rules
-
compare-schemas: Compare schemas between two collections
-
connect-mongodb: Connect to a different MongoDB URI
-
connect-original: Connect back to the original MongoDB URI used at startup
-
count-documents: Count documents matching specified criteria
-
create-collection: Create new collections with custom options
-
create-database: Create a new database with option to switch to it
-
create-index: Create new indexes for performance optimization
-
create-timeseries: Create time series collections for temporal data
-
create-user: Create new database users with specific roles
-
current-database: Show the current database context
-
delete-document: Delete documents matching specified criteria (requires confirmation)
-
distinct-values: Extract unique values for any field
-
drop-collection: Remove collections from the database (requires confirmation)
-
drop-database: Drop a database (requires confirmation)
-
drop-index: Remove indexes from collections (requires confirmation)
-
drop-user: Remove database users (requires confirmation)
-
explain-query: Analyze query execution plans
-
export-data: Export query results in JSON or CSV format
-
find-documents: Run queries with filters, projections, and sorting
-
generate-schema-validator: Generate JSON Schema validators
-
geo-query: Perform geospatial queries with various operators
-
get-stats: Retrieve database or collection statistics
-
gridfs-operation: Manage large files with GridFS buckets
-
insert-document: Insert one or more documents into collections
-
list-collections: Explore collections in the current database
-
list-connections: View all available MongoDB connection aliases
-
list-databases: View all accessible databases
-
[rename-collection: Rename existing collections (](https://github.com/search?type=code&q=repo%3Afurey%2Fmongodb-lens+%2Fserver%5C.tool%5C%28%5Cs*%27r

…

No reviews yet — be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.