- MongoDB Lens
MongoDB Lens
# MongoDB Lens
[\](./LICENSE) [\](https://hub.docker.com/r/furey/mongodb-lens) [\](https://www.npmjs.com/package/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](#quick-start)
- [Features](#features)
- [Installation](#installation)
- [Configuration](#configuration)
- [Client Setup](#client-setup)
- [Tutorial](#tutorial)
- [Disclaimer](#disclaimer)
Quick Start
- Clone repository
- [Install](#installation) dependencies
- [Configure](#configuration) MongoDB Lens
- [Set up](#client-setup) your MCP Client (e.g. [Claude Desktop](#client-setup-claude-desktop))
- Start exploring your MongoDB databases with [natural language queries](#tutorial-example-queries)
Features
- [Resources](#resources)
- [Tools](#tools)
- [Prompts](#prompts)
Resources
- Collection metadata
- Collection statistics
- Collection validation rules
- Database listings
- Database triggers and event configurations
- Database users and roles
- Index information
- Performance metrics and profiling data
- Replica set configuration
- Schema inference
- Server status and metrics
- Stored JavaScript functions
Tools
- `aggregate-data`: Execute aggregation pipelines
- `analyze-schema`: Automatically infer collection schemas
- `bulk-operations`: Perform multiple operations efficiently
- `collation-query`: Find documents with language-specific collation rules
- `count-documents`: Count documents matching specified criteria
- `create-collection`: Create new collections with custom options
- `create-index`: Create new indexes for performance optimization
- `create-timeseries`: Create time series collections for temporal data
- `current-database`: Show the current database context
- `distinct-values`: Extract unique values for any field
- `drop-collection`: Remove collections from the database
- `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
- `geo-query`: Perform geospatial queries with various operators
- `get-stats`: Retrieve database or collection statistics
- `gridfs-operation`: Manage large files with GridFS buckets
- `list-collections`: Explore collections in the current database
- `list-databases`: View all accessible MongoDB databases
- `map-reduce`: Run MapReduce operations for complex data processing
- `modify-document`: Insert, update, or delete specific documents
- `rename-collection`: Rename existing collections
- `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
- `use-database`: Switch to a specific database context
- `validate-collection`: Check for data inconsistencies
- `watch-changes`: Monitor real-time changes to collections
Prompts
- `aggregation-builder`: Step-by-step creation of aggregation pipelines
- `backup-strategy`: Customized backup and recovery recommendations
- `data-modeling`: Expert advice on MongoDB schema design for specific use cases
- `database-health-check`: Comprehensive database health assessment and recommendations
- `index-recommendation`: Get personalized index suggestions based on query patterns
- `inspector-guide`: Get help using MongoDB Lens with MCP Inspector
- `migration-guide`: Step-by-step MongoDB version migration plans
- `mongo-shell`: Generate MongoDB shell commands with explanations
- `multi-tenant-design`: Design MongoDB multi-tenant database architecture
- `query-builder`: Interactive guidance for constructing MongoDB queries
- `query-optimizer`: Optimization recommendations for slow queries
- `schema-analysis`: Detailed collection schema analysis with recommendations
- `schema-versioning`: Manage schema evolution in MongoDB applications
- `security-audit`: Database security analysis and improvement recommendations
- `sql-to-mongodb`: Convert SQL queries to MongoDB aggregation pipelines
Installation
MongoDB Lens can be installed and run in several ways:
- [NPX](#installation-npx) (Easiest)
- [Docker Hub](#installation-docker-hub)
- [Node.js from Source](#installation-nodejs-from-source)
- [Docker from Source](#installation-docker-from-source)
- [Installation Verification](#installation-verification)
Installation: NPX
The easiest way to run MongoDB Lens is using `npx` without installing anything:
```console
Using default connection string mongodb://localhost:27017
npx -y mongodb-lens
Using custom connection string
npx -y mongodb-lens mongodb://your-connection-string ```
Installation: Docker Hub
Run MongoDB Lens directly from Docker Hub without building:
```console
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 ```
Installation: Node.js from Source
-
Navigate to the cloned repository directory:
```console cd /path/to/mongodb-lens ``` -
Ensure [Node](https://nodejs.org/en/download) running (tip: use [Volta](https://volta.sh)):
`$ node -v` >= `22.*` -
Install Node.js dependencies:
```console npm ci ``` -
Start the server (tip: press Ctrl+C to exit):
```consoleUsing 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
-
Navigate to the cloned repository directory:
```console cd /path/to/mongodb-lens ``` -
Build the Docker image:
```console docker build -t mongodb-lens . ``` -
Run the container:
```consoleUsing 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:
```json {"jsonrpc":"2.0","id":1,"method":"resources/read","params":{"uri":"mongodb://databases"}} ```
The server should respond with a list of databases in your MongoDB instance.
MongoDB Lens is now installed and ready to accept MCP requests.
Configuration
- [MongoDB Connection String](#configuration-mongodb-connection-string)
- [Logging](#configuration-logging)
Configuration: MongoDB Connection String
The server accepts a MongoDB connection string as its only argument:
```txt mongodb://[username:password@]host[:port][/database][?options] ```
Example URIs:
- Local connection: `mongodb://localhost:27017`
- Connection with credentials and DB name: `mongodb://username:password@hostname:27017/mydatabase`
- Connection with DB name and options: `mongodb://hostname:27017/mydatabase?retryWrites=true&w=majority`
If no connection string is provided, the server will attempt to connect to MongoDB via local connection:
```txt mongodb://localhost:27017 ```
Configuration: Logging
To enable verbose server logging, set environment variable `VERBOSE_LOGGING` to `true`.
Example Node.js usage:
```console VERBOSE_LOGGING=true node mongodb-lens.js mongodb://your-connection-string ```
Example Docker usage:
```console docker run --rm -i --network=host -e VERBOSE_LOGGING='true' mongodb-lens mongodb://your-connection-string ```
Client Setup
- [Claude Desktop](#client-setup-claude-desktop)
- [MCP Inspector](#client-setup-mcp-inspector)
- [Other MCP Clients](#client-setup-other-mcp-clients)
Client Setup: Claude Desktop
To use MongoDB Lens with Claude Desktop:
- Install [Claude Desktop](https://claude.ai/download)
- Open `claude_desktop_config.json` (create it if it doesn't exist):
- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
- Windows: `%APPDATA%\Claude\claude_desktop_config.json`
- Add the MongoDB Lens server configuration as per [configuration options](#claude-desktop-configuration-options)
- Restart Claude Desktop
- Start a conversation with Claude about your MongoDB data
Claude Desktop Configuration Options
- [Option 1: NPX (Recommended)](#option-1-npx-recommended)
- [Option 2: Docker Hub Image](#option-2-docker-hub-image)
- [Option 3: Local Node.js Installation](#option-3-local-nodejs-installation)
- [Option 4: Local Docker Image](#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`.
- For `VERBOSE_LOGGING`, set to `true` to enable verbose logging or `false` to disable it.
Option 1: NPX (Recommended)
```json { "mcpServers": { "mongodb-lens": { "command": "npx", "args": [ "-y", "mongodb-lens", "mongodb://your-connection-string" ], "env": { "VERBOSE_LOGGING": "[true|false]" } } } } ```
Option 2: Docker Hub Image
```json { "mcpServers": { "mongodb-lens": { "command": "docker", "args": [ "run", "--rm", "-i", "--network=host", "-e", "VERBOSE_LOGGING=[true|false]", "furey/mongodb-lens", "mongodb://your-connection-string" ] } } } ```
Option 3: Local Node.js Installation
```json { "mcpServers": { "mongodb-lens": { "command": "/absolute/path/to/node", "args": [ "/absolute/path/to/mongodb-lens.js", "mongodb://your-connection-string" ], "env": { "VERBOSE_LOGGING": "[true|false]" } } } } ```
Option 4: Local Docker Image
```json { "mcpServers": { "mongodb-lens": { "command": "docker", "args": [ "run", "--rm", "-i", "--network=host", "-e", "VERBOSE_LOGGING=[true|false]", "mongodb-lens", "mongodb://your-connection-string" ] } } } ```
Client Setup: MCP Inspector
[MCP Inspector](https://github.com/modelcontextprotocol/inspector) is a tool designed for testing and debugging MCP servers.
To use MongoDB Lens with MCP Inspector with Node.js from source:
- Navigate to the cloned repository directory:
```console cd /path/to/mongodb-lens ``` - Run Inspector via `npx`:
```console npx -y @modelcontextprotocol/inspector node mongodb-lens.js mongodb://your-connection-string ``` - Inspector starts a proxy server (default port: 3000) and web app (default port: 5173)
- To change the default ports:
```console CLIENT_PORT=8080 SERVER_PORT=9000 npx -y @modelcontextprotocol/inspector node mongodb-lens.js ```
- To change the default ports:
- Open Inspector web app: http://localhost:5173
- Inspector should supports the full range of MongoDB Lens capabilities, including autocompletion for collection names and query fields.
For more, see: [MCP Inspector](https://modelcontextprotocol.io/docs/tools/inspector)
Client Setup: Other MCP Clients
MongoDB Lens can be used with any MCP-compatible client.
For more, see: [MCP Documentation: Example Clients](https://modelcontextprotocol.io/clients)
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:
- [Setting Up Sample Data Container](#tutorial-setting-up-sample-data-container)
- [Importing Sample Data](#tutorial-importing-sample-data)
- [Connecting MongoDB Lens](#tutorial-connecting-mongodb-lens)
- [Example Queries](#tutorial-example-queries)
Tutorial: Setting Up Sample Data Container
IMPORTANT
If you already have a Docker container running on port 27017, stop it before proceeding.
- Initialise sample data container (requires [Docker](https://docs.docker.com/get-started/get-docker/)):
```console docker run --name mongodb-sampledata -d -p 27017:27017 mongo:6 ``` - Verify the container is running without issue:
```console docker ps | grep mongodb-sampledata ```
Tutorial: Importing Sample Data
MongoDB provides several [sample datasets](https://www.mongodb.com/docs/atlas/sample-data/#available-sample-datasets), which we'll use to explore MongoDB Lens.
- Download the sample datasets:
```console
curl -LO https://atlas-education.s3.amazonaws.com/sampledata.archive ``` - Copy the sample datasets into your sample data container:
```console docker cp sampledata.archive mongodb-sampledata:/tmp/ ``` - Restore the sample data:
```console docker exec -it mongodb-sampledata mongorestore --archive=/tmp/sampledata.archive ```
This will import several sample databases including:
- `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: Connecting MongoDB Lens
Download and [install](#installation) MongoDB Lens as per the [Quick Start](#quick-start) instructions.
Set your [MCP Client](#client-setup) to connect to MongoDB Lens with the connection string:
```txt mongodb://localhost:27017 ```
TIP
As the default connection string is `mongodb://localhost:27017`, simply omit it from the client configuration.
For example, if using Claude Desktop set `claude_desktop_config.json` to:
```json { "mcpServers": { "mongodb-lens": { "command": "docker", "args": [ "run", "--rm", "-i", "--network=host", "-e", "VERBOSE_LOGGING=true", "mongodb-lens" ] } } } ```
Tutorial: Example Queries
With your MCP Client running and connected to MongoDB Lens, try these example queries that demonstrate the capabilities of the various tools, resources, and prompts available through MongoDB Lens:
- [Example Queries: Basic Database Operations](#example-queries-basic-database-operations)
- [Example Queries: Movie Data Analysis](#example-queries-movie-data-analysis)
- [Example Queries: Airbnb Data Exploration](#example-queries-airbnb-data-exploration)
- [Example Queries: Weather Data Operations](#example-queries-weather-data-operations)
- [Example Queries: Geospatial Operations](#example-queries-geospatial-operations)
- [Example Queries: Time Series & Change Streams](#example-queries-time-series--change-streams)
- [Example Queries: Bulk Operations & Data Modeling](#example-queries-bulk-operations--data-modeling)
- [Example Queries: Administrative Operations](#example-queries-administrative-operations)
- [Example Queries: Advanced Features](#example-queries-advanced-features)
Example Queries: Basic Database Operations
- _"List all available databases"_
➥ Uses `list-databases` tool - _"What's the current database I'm connected to?"_
➥ Uses `current-database` tool - _"Switch to the sample_mflix database"_
➥ Uses `use-database` tool - _"What collections are available in this database?"_
➥ Uses `list-collections` tool - _"Get statistics for the sample_mflix database"_
➥ Uses `get-stats` tool with database target - _"Create the temp_collection collection, then drop it"_
➥ Uses `create-collection` & `drop-collection` tool
Example Queries: Movie Data Analysis
- _"Count how many movies are in the movies collection"_
➥ Uses `count-documents` tool - _"Find the top 5 movies by IMDB rating with a runtime over 120 minutes"_
➥ Uses `find-documents` tool with sort and filter - _"What's the schema of the movies collection?"_
➥ Uses `analyze-schema` tool - _"Find distinct countries where movies were produced"_
➥ Uses `distinct-values` tool - _"Create an index on the title field in the movies collection"_
➥ Uses `create-index` tool - _"Why is my query for movies with over 1000 votes slow? Help me optimize it"_
➥ Uses `query-optimizer` prompt - _"Run an explain on the query {year: 1995}"_
➥ Uses `explain-query` tool - _"Build an aggregation pipeline to show the count of movies by decade and genre"_
➥ Uses `aggregation-builder` prompt - _"Execute this aggregation pipeline: [{$group: {\_id: {$floor: {$divide: ['$year', 10]}}, count: {$sum: 1}}}]"_
➥ Uses `aggregate-data` tool - _"Update all movies from 1994 to add a 'classic' field set to true"_
➥ Uses `modify-document` tool with update operation
Example Queries: Airbnb Data Exploration
- _"Switch to sample_airbnb database"_
➥ Uses `use-database` tool - _"Get collection statistics for the listingsAndReviews collection"_
➥ Uses `get-stats` tool with collection target - _"What's the validation rules for the listingsAndReviews collection?"_
➥ Uses `collection-validation` resource - _"Show me the indexes on the listingsAndReviews collection"_
➥ Uses `collection-indexes` resource - _"Find listings with more than 5 bedrooms in Manhattan, limited to 10 results"_
➥ Uses `find-documents` tool - _"Get distinct property types in the listings"_
➥ Uses `distinct-values` tool - _"Help me create a query filter to find superhosts with pool amenities"_
➥ Uses `query-builder` prompt - _"Export the top 20 highest-rated listings in Brooklyn as CSV with name, price, and rating"_
➥ Uses `export-data` tool - _"Is my schema optimized for querying by neighborhood? Analyze and give recommendations"_
➥ Uses `schema-analysis` prompt - _"Rename the reviews collection to guest_reviews"_
➥ Uses `rename-collection` tool
Example Queries: Weather Data Operations
- _"Switch to sample_weatherdata database"_
➥ Uses `use-database` tool - _"What's in the schema of the data collection?"_
➥ Uses `collection-schema` resource - _"Find the highest recorded temperatures with a callLetters of 'SHIP'"_
➥ Uses `find-documents` tool - _"Validate the data collection for inconsistencies"_
➥ Uses `validate-collection` tool - _"Insert a new weather record for today"_
➥ Uses `modify-document` tool with insert operation - _"Create a new collection called weather_summary"_
➥ Uses `create-collection` tool - _"Create index recommendation for queries that filter by callLetters and sort by date"_
➥ Uses `index-recommendation` prompt - _"Show me how to write a MapReduce operation to get average temperatures by day"_
➥ Uses `mongo-shell` prompt - _"Run this MapReduce to calculate average pressure by location"_
➥ Uses `map-reduce` tool - _"Delete all weather readings below -50 degrees"_
➥ Uses `modify-document` tool with delete operation
Example Queries: Geospatial Operations
- _"Switch to sample_geospatial database"_
➥ Uses `use-database` tool - _"Find all shipwrecks within 5km of the coast of Florida"_
➥ Uses `geo-query` tool with near operator - _"Show me restaurants that fall within the downtown Manhattan polygon"_
➥ Uses `geo-query` tool with geoWithin operator - _"Which bike routes intersect with Central Park?"_
➥ Uses `geo-query` tool with geoIntersects operator - _"Create a geospatial index on the location field of the neighborhoods collection"_
➥ Uses `create-index` tool with 2dsphere index type - _"Analyze the schema of the shipwrecks collection to understand its geospatial data structure"_
➥ Uses `analyze-schema` tool
Example Queries: Time Series & Change Streams
- _"Create a new time series collection for sensor readings with 'timestamp' as the time field"_
➥ Uses `create-timeseries` tool - _"Watch for changes in the orders collection for the next 30 seconds"_
➥ Uses `watch-changes` tool - _"Monitor all insert operations on the users collection for 15 seconds"_
➥ Uses `watch-changes` tool with specific operations - _"Create a time series collection for IoT device data with hourly granularity"_
➥ Uses `create-timeseries` tool with granularity option - _"Create a time series collection that automatically deletes data older than 30 days"_
➥ Uses `create-timeseries` tool with expireAfterSeconds option
Example Queries: Bulk Operations & Data Modeling
- _"Switch to sample_training database"_
➥ Uses `use-database` tool - _"Execute a bulk operation to update multiple post documents to add 'edited' flags"_
➥ Uses `bulk-operations` tool - _"How should I model a social media application in MongoDB?"_
➥ Uses `data-modeling` prompt - _"Perform a bulk insertion of new product records in the supplies database"_
➥ Uses `bulk-operations` tool - _"Show me how to use MongoDB Lens with the MCP Inspector"_
➥ Uses `inspector-guide` prompt - _"What's the optimal data model for a multi-tenant SaaS application with heavy analytical queries?"_
➥ Uses `data-modeling` prompt
Example Queries: Administrative Operations
- _"Switch to the admin database"_
➥ Uses `use-database` tool - _"Show me the server status"_
➥ Uses `server-status` resource - _"Display the replica set configuration"_
➥ Uses `replica-status` resource - _"List all users in the database"_
➥ Uses `database-users` resource - _"Get any stored JavaScript functions"_
➥ Uses `stored-functions` resource - _"Perform a security audit on my MongoDB deployment"_
➥ Uses `security-audit` prompt - _"What's a good backup strategy for my MongoDB instance?"_
➥ Uses `backup-strategy` prompt - _"How would I migrate from MongoDB 4.4 to 6.0?"_
➥ Uses `migration-guide` prompt
Example Queries: Advanced Features
- _"Switch to sample_mflix database"_
➥ Uses `use-database` tool - _"Search for movies containing the phrase 'space odyssey' using text search"_
➥ Uses `text-search` tool - _"Find users named 'müller' using German collation rules"_
➥ Uses `collation-query` tool - _"List all files in the images GridFS bucket"_
➥ Uses `gridfs-operation` tool with list operation - _"Get detailed information about the 'profile.jpg' file in GridFS"_
➥ Uses `gridfs-operation` tool with info operation - _"Delete the 'old_backup.zip' file from the files GridFS bucket"_
➥ Uses `gridfs-operation` tool with delete operation - _"Check the sharding status of the sample_analytics database"_
➥ Uses `shard-status` tool with database target - _"View the sharding distribution for the customers collection"_
➥ Uses `shard-status` tool with collection target - _"Execute a transaction that transfers $100 from account A to account B"_
➥ Uses `transaction` tool - _"Get real-time performance metrics for my MongoDB server"_
➥ Uses `performance-metrics` resource - _"Show me the current event triggers in my database"_
➥ Uses `database-triggers` resource - _"Convert this SQL query to MongoDB: SELECT * FROM users WHERE age > 30 ORDER BY name"_
➥ Uses `sql-to-mongodb` prompt - _"Perform a comprehensive health check on my database"_
➥ Uses `database-health-check` prompt - _"Help me design a multi-tenant architecture for my SaaS application"_
➥ Uses `multi-tenant-design` prompt - _"I need to add user address fields to my schema. How should I version and migrate?"_
➥ Uses `schema-versioning` prompt
Disclaimer
MongoDB Lens:
- is licensed under the [MIT License](./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 or support—use at your own risk.