MongoDB Lens
hybrid server
The server is able to function both locally and remotely, depending on the configuration or use case.
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
MongoDB Lens exposes the following capabilities through MCP:
Resources
- Collection metadata
- Collection statistics
- Collection validation rules
- Database listings
- Database users and roles
- Index information
- Replica set configuration
- Schema inference
- Server status and metrics
- Stored JavaScript functions
Tools
aggregate-data
: Execute aggregation pipelinesanalyze-schema
: Automatically infer collection schemasbulk-operations
: Perform multiple operations efficientlycount-documents
: Count documents matching specified criteriacreate-collection
: Create new collections with custom optionscreate-index
: Create new indexes for performance optimizationcurrent-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 sortingget-stats
: Retrieve database or collection statisticslist-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 collectionsuse-database
: Switch to a specific database contextvalidate-collection
: Check for data inconsistencies
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 casesindex-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 explanationsquery-builder
: Interactive guidance for constructing MongoDB queriesquery-optimizer
: Optimization recommendations for slow queriesschema-analysis
: Detailed collection schema analysis with recommendationssecurity-audit
: Database security analysis and improvement recommendations
Installation
MongoDB Lens can run via Docker or Node.js.
Depending on your preference, follow the installation instructions below:
Docker Installation
- Navigate to the cloned repository directory:<br>Copy
- Build the Docker image:<br>Copy
- Check the installation runs (tip: press <kbd>Ctrl</kbd>+<kbd>C</kbd> to exit):<br>Copy
- Verify the server installation by sending a test message.
Node.js Installation
- Navigate to the cloned repository directory:<br>Copy
- Ensure Node running (tip: use Volta):<br>
$ node -v
>=22.*
- Install Node.js dependencies:<br>Copy
- Start the server (tip: press <kbd>Ctrl</kbd>+<kbd>C</kbd> to exit):<br>Copy
- Verify the server installation by sending a test message.
Installation Verification
To verify the installation, paste and run the following jsonrpc message into the server's stdio:
The server should respond with a list of databases in your MongoDB instance, e.g.:<br>
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 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:
Configuration: Logging
To enable verbose server logging, set environment variable VERBOSE_LOGGING
to true
.
Example Node.js usage:
Example Docker usage:
Client Setup
Client Setup: Claude Desktop
To use MongoDB Lens with Claude Desktop:
- Install Claude Desktop
- Create and/or open
claude_desktop_config.json
:- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json
- Windows:
%APPDATA%\Claude\claude_desktop_config.json
- macOS:
- Add the MongoDB Lens server configuration:
- Example Docker configuration:<br>Copy
- Replace
mongodb://your-connection-string
with your MongoDB connection string - Set
VERBOSE_LOGGING
totrue
for verbose MCP Server logs
- Replace
- Example Node.js configuration:<br>Copy
- Replace
/absolute/path/to/node
with the full path tonode
- Replace
/absolute/path/to/mongodb-lens.js
with the full file path tomongodb-lens.js
- Replace
mongodb://your-connection-string
with your MongoDB connection string - Set
VERBOSE_LOGGING
totrue
for verbose MCP Server logs
- Replace
- Example Docker configuration:<br>
- Restart Claude Desktop
- Start a conversation with Claude about your MongoDB data
- Claude will show a hammer icon indicating available tools
- See example queries for conversation inspiration
Client Setup: MCP Inspector
MCP Inspector is a tool designed for testing and debugging MCP servers.
To use MongoDB Lens with MCP Inspector:
- Navigate to the cloned repository directory:<br>Copy
- Run Inspector via
npx
:<br>Copy - Inspector starts a proxy server (default port: 3000) and web app (default port: 5173)
- To change the default ports:<br>Copy
- To change the default ports:<br>
- 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
Client Setup: Other MCP Clients
MongoDB Lens can be used 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: Setting Up Sample Data Container
[!IMPORTANT]<br> If you already have a Docker container running on port 27017, stop it before proceeding.
- Initialise sample data container (requires Docker):<br>Copy
- Verify the container is running without issue:<br>Copy
Tutorial: Importing Sample Data
MongoDB provides several sample datasets, which we'll use to explore MongoDB Lens.
- Download the sample datasets:Copy
- Copy the sample datasets into your sample data container:<br>Copy
- Restore the sample data:<br>Copy
This will import several sample databases including:
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: Connecting MongoDB Lens
Download and install MongoDB Lens as per the Quick Start instructions.
Set your MCP Client to connect to MongoDB Lens with the connection string:
[!TIP]<br> 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:
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: Movie Data Analysis
- Example Queries: Airbnb Data Exploration
- Example Queries: Weather Data Operations
- Example Queries: Bulk Operations & Data Modeling
- Example Queries: Administrative Operations
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: 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>
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.
This server cannot be installed
Full featured MCP Server for MongoDB database analysis.