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
- Clone repository
- Install dependencies
- Configure MongoDB Lens
- Set up your MCP Client (e.g. Claude Desktop)
- Start exploring your MongoDB databases with natural language queries
Features
Tools
aggregate-data
: Execute aggregation pipelines (with streaming support for large result sets)analyze-query-patterns
: Analyze queries and suggest optimizationsanalyze-schema
: Automatically infer collection schemasbulk-operations
: Perform multiple operations efficientlycollation-query
: Find documents with language-specific collation rulescompare-schemas
: Compare schemas between two collectionscount-documents
: Count documents matching specified criteriacreate-collection
: Create new collections with custom optionscreate-index
: Create new indexes for performance optimizationcreate-timeseries
: Create time series collections for temporal datacurrent-database
: Show the current database contextdistinct-values
: Extract unique values for any fielddrop-collection
: Remove collections from the databaseexplain-query
: Analyze query execution plansexport-data
: Export query results in JSON or CSV formatfind-documents
: Run queries with filters, projections, and sorting (with streaming for large result sets)generate-schema-validator
: Generate JSON Schema validatorsgeo-query
: Perform geospatial queries with various operatorsget-stats
: Retrieve database or collection statisticsgridfs-operation
: Manage large files with GridFS bucketslist-collections
: Explore collections in the current databaselist-databases
: View all accessible MongoDB databasesmap-reduce
: Run MapReduce operations for complex data processingmodify-document
: Insert, update, or delete specific documentsrename-collection
: Rename existing collectionsshard-status
: View sharding configuration for databases and collectionstext-search
: Perform full-text search across text-indexed fieldstransaction
: Execute multiple operations in a single ACID transactionuse-database
: Switch to a specific database contextvalidate-collection
: Check for data inconsistencieswatch-changes
: Monitor real-time changes to collections
Resources
collection-indexes
: Index information for a collectioncollection-schema
: Schema information for a collectioncollection-stats
: Performance statistics for a collectioncollection-validation
: Validation rules for a collectioncollections
: List of collections in the current databasedatabase-triggers
: Database change streams and event triggers configurationdatabase-users
: Database users and roles in the current databasedatabases
: List of all accessible databasesperformance-metrics
: Real-time performance metrics and profiling datareplica-status
: Replica set status and configurationserver-status
: Server status informationstored-functions
: Stored JavaScript functions in the current database
Prompts
aggregation-builder
: Step-by-step creation of aggregation pipelinesbackup-strategy
: Customized backup and recovery recommendationsdata-modeling
: Expert advice on MongoDB schema design for specific use casesdatabase-health-check
: Comprehensive database health assessment and recommendationsindex-recommendation
: Get personalized index suggestions based on query patternsinspector-guide
: Get help using MongoDB Lens with MCP Inspectormigration-guide
: Step-by-step MongoDB version migration plansmongo-shell
: Generate MongoDB shell commands with explanationsmulti-tenant-design
: Design MongoDB multi-tenant database architecturequery-builder
: Interactive guidance for constructing MongoDB queriesquery-optimizer
: Optimization recommendations for slow queriesschema-analysis
: Detailed collection schema analysis with recommendationsschema-versioning
: Manage schema evolution in MongoDB applicationssecurity-audit
: Database security analysis and improvement recommendationssql-to-mongodb
: Convert SQL queries to MongoDB aggregation pipelines
Performance Features
- Sanitized Inputs: Security enhancements for query processing
- Connection Resilience: Automatic reconnection with exponential backoff
- Configuration File: Custom configuration via
~/.mongodb-lens.json
- JSONRPC Error Handling: Comprehensive error handling with proper error codes
- Memory Management: Automatic memory monitoring and cleanup for large operations
- Smart Caching: Enhanced caching for schemas, collection lists, and server status
- Streaming Support: Stream large result sets for
find-documents
andaggregate-data
operations
Installation
MongoDB Lens can be installed and run in several ways:
Installation: NPX
The easiest way to run MongoDB Lens is using npx
without installing anything:
# Using default connection string mongodb://localhost:27017
npx -y mongodb-lens
# Using custom connection string
npx -y mongodb-lens mongodb://your-connection-string
[!TIP]<br> If you encounter permissions errors with
npx
, try runningnpx clear-npx-cache
prior to runningnpx -y mongodb-lens
(this clears the cache and re-downloads the package).
Installation: Docker Hub
Run MongoDB Lens directly from Docker Hub without building:
# Using default connection string mongodb://localhost:27017
docker run --rm -i --network=host furey/mongodb-lens
# Using "--pull" to keep the Docker image up-to-date
docker run --rm -i --network=host --pull=always 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:<br>
cd /path/to/mongodb-lens
- Ensure Node running (suggestion: use Volta):<br>
$ node -v
>=22.*
- Install Node.js dependencies:<br>
npm ci
- Start the server:<br>
# 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
- Navigate to the cloned repository directory:<br>
cd /path/to/mongodb-lens
- Build the Docker image:<br>
docker build -t mongodb-lens .
- Run the container:<br>
# 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.
Shut down the server by sending a SIGINT
signal (<kbd>Ctrl</kbd>+<kbd>C</kbd>).
Configuration
Configuration: MongoDB Connection String
The server accepts a MongoDB connection string as its only argument.
Example NPX usage:
npx -y mongodb-lens mongodb://your-connection-string
MongoDB connection strings have the following format:
mongodb://[username:password@]host[:port][/database][?options]
Example connection strings:
- Local connection:<br>
mongodb://localhost:27017
- Connection to
mydatabase
with credentials fromadmin
database:<br>mongodb://username:password@hostname:27017/mydatabase?authSource=admin
- Connection to
mydatabase
with various other options:<br>mongodb://hostname:27017/mydatabase?retryWrites=true&w=majority
If no connection string is provided, the server will attempt to connect via local connection.
Configuration: Verbose Logging
To enable verbose logging, set environment variable VERBOSE_LOGGING
to true
.
Example NPX usage:
VERBOSE_LOGGING=true npx -y mongodb-lens mongodb://your-connection-string
Example Docker Hub usage:
docker run --rm -i --network=host -e VERBOSE_LOGGING='true' furey/mongodb-lens mongodb://your-connection-string
With verbose logging enabled, the server will output additional information to the console.
Configuration: Config File
MongoDB Lens can also be configured via JSON config file: ~/.mongodb-lens.json
Alternatively, set environment variable CONFIG_PATH
to the path of your custom config file.
Example NPX usage:
CONFIG_PATH='/path/to/config.json' npx -y mongodb-lens
Example Docker Hub usage:
docker run --rm -i --network=host -v /path/to/config.json:/root/.mongodb-lens.json furey/mongodb-lens
Example configuration file contents:
{
"mongoUri": "mongodb://username:password@hostname:27017/mydatabase?authSource=admin",
"connectionOptions": {
"maxPoolSize": 20,
"connectTimeoutMS": 30000
}
}
Client Setup
Client Setup: Claude Desktop
To use MongoDB Lens with Claude Desktop:
- Install Claude Desktop
- 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
- macOS:
- Add the MongoDB Lens server configuration as per configuration options
- Restart Claude Desktop
- Start a conversation with Claude about your MongoDB data
Claude Desktop Configuration Options
- Option 1: NPX (Recommended)
- Option 2: Docker Hub Image
- Option 3: Local Node.js Installation
- Option 4: Local Docker Image
For each option:
- Replace
mongodb://your-connection-string
with your MongoDB connection string or omit it to use the defaultmongodb://localhost:27017
. - Set
VERBOSE_LOGGING
totrue
orfalse
. - To use a custom config file, see Configuration: Config File and adapt option accordingly.
Option 1: NPX (Recommended)
{
"mcpServers": {
"mongodb-lens": {
"command": "/path/to/npx",
"args": [
"-y",
"mongodb-lens",
"mongodb://your-connection-string"
],
"env": {
"VERBOSE_LOGGING": "[true|false]"
}
}
}
}
Option 2: Docker Hub Image
{
"mcpServers": {
"mongodb-lens": {
"command": "docker",
"args": [
"run",
"--rm",
"-i",
"--network=host",
"--pull=always",
"-e",
"VERBOSE_LOGGING=[true|false]",
"furey/mongodb-lens",
"mongodb://your-connection-string"
]
}
}
}
Option 3: Local Node.js Installation
{
"mcpServers": {
"mongodb-lens": {
"command": "/path/to/node",
"args": [
"/path/to/mongodb-lens.js",
"mongodb://your-connection-string"
],
"env": {
"VERBOSE_LOGGING": "[true|false]"
}
}
}
}
Option 4: Local Docker Image
{
"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 is a tool designed for testing and debugging MCP servers.
Example Node.js from source usage:
- Navigate to the cloned repository directory:<br>
cd /path/to/mongodb-lens
- Run Inspector via
npx
:<br>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:<br>
CLIENT_PORT=8080 SERVER_PORT=9000 npx -y @modelcontextprotocol/inspector node mongodb-lens.js
- To change the default ports:<br>
- Open Inspector web app: http://localhost:5173
- 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
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:
Tutorial: 1. Start Sample Data Container
[!NOTE]<br> This tutorial assumes you have Docker installed and running on your system.
[!IMPORTANT]<br> If Docker is already running a container on port 27017, stop it before proceeding.
- Initialise sample data container:<br>
docker run --name mongodb-sampledata -d -p 27017:27017 mongo:6
- Verify the container is running without issue:<br>
docker ps | grep mongodb-sampledata
Tutorial: 2. Import Sample Data
MongoDB provides several sample datasets, which we'll use to explore MongoDB Lens.
- Download the sample datasets:
curl -LO https://atlas-education.s3.amazonaws.com/sampledata.archive
- Copy the sample datasets into your sample data container:<br>
docker cp sampledata.archive mongodb-sampledata:/tmp/
- Restore the sample data into MongoDB:<br>
docker exec -it mongodb-sampledata mongorestore --archive=/tmp/sampledata.archive
This will import several databases:
sample_airbnb
: Airbnb listings and reviewssample_analytics
: Customer and account datasample_geospatial
: Geographic datasample_mflix
: Movie datasample_restaurants
: Restaurant datasample_supplies
: Supply chain datasample_training
: Training data for various applicationssample_weatherdata
: Weather measurements
Tutorial: 3. Connect MongoDB Lens
Download and install MongoDB Lens as per the Quick Start instructions.
Set your MCP Client to connect to MongoDB Lens via: mongodb://localhost:27017
[!TIP]<br> Omitting the connection string from your MCP Client configuration will default the connection string to
mongodb://localhost:27017
.
Example Claude Desktop configuration:
{
"mcpServers": {
"mongodb-lens": {
"command": "/path/to/npx",
"args": [
"-y",
"mongodb-lens"
]
}
}
}
Tutorial: 4. 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: Movie Data Analysis
- Example Queries: Airbnb Data Exploration
- Example Queries: Weather Data Operations
- Example Queries: Geospatial Operations
- Example Queries: Time Series & Change Streams
- Example Queries: Bulk Operations & Data Modeling
- Example Queries: Administrative Operations
- Example Queries: Advanced Features
Example Queries: Basic Database Operations
- "List all available databases"<br>
<sup>➥ Uses
list-databases
tool</sup> - "What's the current database I'm connected to?"<br>
<sup>➥ Uses
current-database
tool</sup> - "Switch to the sample_mflix database"<br>
<sup>➥ Uses
use-database
tool</sup> - "What collections are available in this database?"<br>
<sup>➥ Uses
list-collections
tool</sup> - "Get statistics for the sample_mflix database"<br>
<sup>➥ Uses
get-stats
tool with database target</sup> - "Create the temp_collection collection, then drop it"<br>
<sup>➥ Uses
create-collection
&drop-collection
tool</sup>
Example Queries: Movie Data Analysis
- "Count how many movies are in the movies collection"<br>
<sup>➥ Uses
count-documents
tool</sup> - "Find the top 5 movies by IMDB rating with a runtime over 120 minutes"<br>
<sup>➥ Uses
find-documents
tool with sort and filter</sup> - "What's the schema of the movies collection?"<br>
<sup>➥ Uses
analyze-schema
tool</sup> - "Find distinct countries where movies were produced"<br>
<sup>➥ Uses
distinct-values
tool</sup> - "Create an index on the title field in the movies collection"<br>
<sup>➥ Uses
create-index
tool</sup> - "Why is my query for movies with over 1000 votes slow? Help me optimize it"<br>
<sup>➥ Uses
query-optimizer
prompt</sup> - "Run an explain on the query {year: 1995}"<br>
<sup>➥ Uses
explain-query
tool</sup> - "Build an aggregation pipeline to show the count of movies by decade and genre"<br>
<sup>➥ Uses
aggregation-builder
prompt</sup> - "Execute this aggregation pipeline: [{$group: {_id: {$floor: {$divide: ['$year', 10]}}, count: {$sum: 1}}}]"<br>
<sup>➥ Uses
aggregate-data
tool</sup> - "Update all movies from 1994 to add a 'classic' field set to true"<br>
<sup>➥ Uses
modify-document
tool with update operation</sup>
Example Queries: Airbnb Data Exploration
- "Switch to sample_airbnb database"<br>
<sup>➥ Uses
use-database
tool</sup> - "Get collection statistics for the listingsAndReviews collection"<br>
<sup>➥ Uses
get-stats
tool with collection target</sup> - "What's the validation rules for the listingsAndReviews collection?"<br>
<sup>➥ Uses
collection-validation
resource</sup> - "Show me the indexes on the listingsAndReviews collection"<br>
<sup>➥ Uses
collection-indexes
resource</sup> - "Find listings with more than 5 bedrooms in Manhattan, limited to 10 results"<br>
<sup>➥ Uses
find-documents
tool</sup> - "Get distinct property types in the listings"<br>
<sup>➥ Uses
distinct-values
tool</sup> - "Help me create a query filter to find superhosts with pool amenities"<br>
<sup>➥ Uses
query-builder
prompt</sup> - "Export the top 20 highest-rated listings in Brooklyn as CSV with name, price, and rating"<br>
<sup>➥ Uses
export-data
tool</sup> - "Is my schema optimized for querying by neighborhood? Analyze and give recommendations"<br>
<sup>➥ Uses
schema-analysis
prompt</sup> - "Rename the reviews collection to guest_reviews"<br>
<sup>➥ Uses
rename-collection
tool</sup>
Example Queries: Weather Data Operations
- "Switch to sample_weatherdata database"<br>
<sup>➥ Uses
use-database
tool</sup> - "What's in the schema of the data collection?"<br>
<sup>➥ Uses
collection-schema
resource</sup> - "Find the highest recorded temperatures with a callLetters of 'SHIP'"<br>
<sup>➥ Uses
find-documents
tool</sup> - "Validate the data collection for inconsistencies"<br>
<sup>➥ Uses
validate-collection
tool</sup> - "Insert a new weather record for today"<br>
<sup>➥ Uses
modify-document
tool with insert operation</sup> - "Create a new collection called weather_summary"<br>
<sup>➥ Uses
create-collection
tool</sup> - "Create index recommendation for queries that filter by callLetters and sort by date"<br>
<sup>➥ Uses
index-recommendation
prompt</sup> - "Show me how to write a MapReduce operation to get average temperatures by day"<br>
<sup>➥ Uses
mongo-shell
prompt</sup> - "Run this MapReduce to calculate average pressure by location"<br>
<sup>➥ Uses
map-reduce
tool</sup> - "Delete all weather readings below -50 degrees"<br>
<sup>➥ Uses
modify-document
tool with delete operation</sup>
Example Queries: Geospatial Operations
- "Switch to sample_geospatial database"<br>
<sup>➥ Uses
use-database
tool</sup> - "Find all shipwrecks within 5km of the coast of Florida"<br>
<sup>➥ Uses
geo-query
tool with near operator</sup> - "Show me restaurants that fall within the downtown Manhattan polygon"<br>
<sup>➥ Uses
geo-query
tool with geoWithin operator</sup> - "Which bike routes intersect with Central Park?"<br>
<sup>➥ Uses
geo-query
tool with geoIntersects operator</sup> - "Create a geospatial index on the location field of the neighborhoods collection"<br>
<sup>➥ Uses
create-index
tool with 2dsphere index type</sup> - "Analyze the schema of the shipwrecks collection to understand its geospatial data structure"<br>
<sup>➥ Uses
analyze-schema
tool</sup>
Example Queries: Time Series & Change Streams
- "Create a new time series collection for sensor readings with 'timestamp' as the time field"<br>
<sup>➥ Uses
create-timeseries
tool</sup> - "Watch for changes in the orders collection for the next 30 seconds"<br>
<sup>➥ Uses
watch-changes
tool</sup> - "Monitor all insert operations on the users collection for 15 seconds"<br>
<sup>➥ Uses
watch-changes
tool with specific operations</sup> - "Create a time series collection for IoT device data with hourly granularity"<br>
<sup>➥ Uses
create-timeseries
tool with granularity option</sup> - "Create a time series collection that automatically deletes data older than 30 days"<br>
<sup>➥ Uses
create-timeseries
tool with expireAfterSeconds option</sup>
Example Queries: Bulk Operations & Data Modeling
- "Switch to sample_training database"<br>
<sup>➥ Uses
use-database
tool</sup> - "Execute a bulk operation to update multiple post documents to add 'edited' flags"<br>
<sup>➥ Uses
bulk-operations
tool</sup> - "How should I model a social media application in MongoDB?"<br>
<sup>➥ Uses
data-modeling
prompt</sup> - "Perform a bulk insertion of new product records in the supplies database"<br>
<sup>➥ Uses
bulk-operations
tool</sup> - "Show me how to use MongoDB Lens with the MCP Inspector"<br>
<sup>➥ Uses
inspector-guide
prompt</sup> - "What's the optimal data model for a multi-tenant SaaS application with heavy analytical queries?"<br>
<sup>➥ Uses
data-modeling
prompt</sup>
Example Queries: Administrative Operations
- "Switch to the admin database"<br>
<sup>➥ Uses
use-database
tool</sup> - "Show me the server status"<br>
<sup>➥ Uses
server-status
resource</sup> - "Display the replica set configuration"<br>
<sup>➥ Uses
replica-status
resource</sup> - "List all users in the database"<br>
<sup>➥ Uses
database-users
resource</sup> - "Get any stored JavaScript functions"<br>
<sup>➥ Uses
stored-functions
resource</sup> - "Perform a security audit on my MongoDB deployment"<br>
<sup>➥ Uses
security-audit
prompt</sup> - "What's a good backup strategy for my MongoDB instance?"<br>
<sup>➥ Uses
backup-strategy
prompt</sup> - "How would I migrate from MongoDB 4.4 to 6.0?"<br>
<sup>➥ Uses
migration-guide
prompt</sup>
Example Queries: Schema Management & Analysis
- "Compare schemas between the users and customers collections"<br>
<sup>➥ Uses new
compare-schemas
tool to identify differences</sup> - "Generate a JSON Schema validator for the profiles collection with moderate strictness"<br>
<sup>➥ Uses new
generate-schema-validator
tool</sup> - "Analyze query patterns for the orders collection"<br>
<sup>➥ Uses new
analyze-query-patterns
tool</sup> - "What fields are missing in the new customers collection compared to the old one?"<br>
<sup>➥ Uses
compare-schemas
to analyze migration gaps</sup> - "Are my indexes being used effectively for my queries?"<br>
<sup>➥ Uses
analyze-query-patterns
to identify optimization opportunities</sup>
Example Queries: Advanced Features
- "Switch to sample_mflix database"<br>
<sup>➥ Uses
use-database
tool</sup> - "Search for movies containing the phrase 'space odyssey' using text search"<br>
<sup>➥ Uses
text-search
tool</sup> - "Find users named 'müller' using German collation rules"<br>
<sup>➥ Uses
collation-query
tool</sup> - "List all files in the images GridFS bucket"<br>
<sup>➥ Uses
gridfs-operation
tool with list operation</sup> - "Get detailed information about the 'profile.jpg' file in GridFS"<br>
<sup>➥ Uses
gridfs-operation
tool with info operation</sup> - "Delete the 'old_backup.zip' file from the files GridFS bucket"<br>
<sup>➥ Uses
gridfs-operation
tool with delete operation</sup> - "Check the sharding status of the sample_analytics database"<br>
<sup>➥ Uses
shard-status
tool with database target</sup> - "View the sharding distribution for the customers collection"<br>
<sup>➥ Uses
shard-status
tool with collection target</sup> - "Execute a transaction that transfers $100 from account A to account B"<br>
<sup>➥ Uses
transaction
tool</sup> - "Get real-time performance metrics for my MongoDB server"<br>
<sup>➥ Uses
performance-metrics
resource</sup> - "Show me the current event triggers in my database"<br>
<sup>➥ Uses
database-triggers
resource</sup> - "Convert this SQL query to MongoDB: SELECT * FROM users WHERE age > 30 ORDER BY name"<br>
<sup>➥ Uses
sql-to-mongodb
prompt</sup> - "Perform a comprehensive health check on my database"<br>
<sup>➥ Uses
database-health-check
prompt</sup> - "Help me design a multi-tenant architecture for my SaaS application"<br>
<sup>➥ Uses
multi-tenant-design
prompt</sup> - "I need to add user address fields to my schema. How should I version and migrate?"<br>
<sup>➥ Uses
schema-versioning
prompt</sup>
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 or support—use at your own risk.