Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /

Comienza con el servidor MCP de MongoDB

En esta guía, aprenderá cómo empezar con el servidor MCP de MongoDB configurándolo y usándolo en su cliente de IA.

Para utilizar el servidor MCP de MongoDB, debes tener lo siguiente:

  • Un clúster de Atlas o una implementación de MongoDB autoalojada.

    Para aprender más, Crea un Clúster o Instala MongoDB.

  • Cualquier cliente MCP compatible.

  • Node.js instalado, usando una de las siguientes versiones:

    • Versión 20.19.0 o posterior.

    • Si utilizas la versión 22, debe usar la versión 22.12.0 o una posterior.

    • De lo contrario, utiliza la versión 23 o una posterior.

    Nota

    Como alternativa, puedes ejecutar el servidor en un contenedor Docker, lo cual no requiere instalar Node.js. Para obtener más información, consulta Uso de Docker.

Si utiliza Claude Code, Cursor o Gemini, puede instalar el servidor MCP de MongoDB como parte del complemento o extensión oficial de MongoDB para su cliente de IA. Estos paquetes incluyen el servidor MCP de MongoDB y habilidades de agente preconfiguradas para tareas comunes de MongoDB. Para obtener más información, consulte la documentación de las habilidades de agente de MongoDB.

Cliente
Opción de instalación
Paquete incluido

Claude Code

Instala el plugin oficial MongoDB Claude desde el Anthropic Plugin Marketplace. Consulta MongoDB con Claude para obtener más información.

Incluye el servidor MongoDB MCP y las funcionalidades de agente preconfiguradas.

Cursor

Instala el plugin oficial de MongoDB Cursor desde el Marketplace de plugins de Cursor. Consulta MongoDB con Cursor para obtener más información.

Incluye el servidor MongoDB MCP y las funcionalidades de agente preconfiguradas.

Gemini

Instala la extensión oficial de MongoDB Gemini desde el Gemini Extension Marketplace. Consulta MongoDB con Gemini para obtener más información.

Incluye el servidor MongoDB MCP y las funcionalidades de agente preconfiguradas.

Después de instalar uno de estos paquetes, continúe con la siguiente sección para configurar el servidor MCP de MongoDB para su implementación de MongoDB.

También necesitas la siguiente información del clúster de MongoDB:

  • Cadena de conexión. Para obtener más información, consulte la sección "Cómo encontrar su cadena de conexión".

  • Si utiliza Atlas con una cuenta de servicio, necesita el ID de cliente y el secreto de cliente de su cuenta de servicio de Atlas. Para ver los requisitos previos de Atlas, consulte Requisitos previos del atlas.

El archivo de configuración JSON del servidor MCP de MongoDB le indica al servidor cómo conectarse a MongoDB y cómo compartir esos datos con los clientes MCP.

Para crear un archivo JSON inicial, utilice la utilidad de configuración del servidor MCP. Esta utilidad le guiará a través del proceso de configuración. Siga estos pasos:

1

Desde la línea de comandos, ejecute:

npx mongodb-mcp-server@latest setup
2

Seleccione su cliente de IA de la lista de clientes compatibles que muestra la utilidad. Por ejemplo, seleccione VS Code.

Algunos ejemplos de clientes son:

  • Cursor

  • VS Code

  • Claude Desktop

  • Claude Code

  • Código abierto

  • Windsurf

Si utiliza un cliente que no figura en la lista, deberá configurar el archivo JSON manualmente. Para obtener más información, consulte la sección "Configuración manual de archivos del servidor MCP de MongoDB".

3

Puede limitar el servidor MCP para que realice únicamente operaciones de lectura mediante el modo de solo lectura. Para habilitar el modo de solo lectura, introduzca Y.

Por motivos de seguridad, active siempre el modo de solo lectura, salvo que necesite realizar operaciones de escritura. Puede activar las operaciones de escritura posteriormente. Para obtener más información, consulte el apartado Modo de solo lectura del servidor MCP.

4

Introduzca la cadena de conexión para su clúster de MongoDB.

Por ejemplo, mongodb+srv://atlasuser:D1fficultP%40ssw0rd@mycluster.abcd1.mongodb.net/myDatabase?retryWrites=true&w=majority.

Para obtener más información, se debe consultar Encontrar la cadena de conexión.

5

Si utiliza un clúster de Atlas con una cuenta de servicio, introduzca el identificador de cliente de su cuenta de servicio de Atlas.

Para obtener más detalles, consulte la cuenta de servicio de Atlas.

Ejemplo de formato de identificador de cliente de cuenta de servicio de Atlas: mdb_sa_id_<objectId>.

6

Si utiliza un clúster de Atlas con una cuenta de servicio, introduzca la clave secreta de cliente de su cuenta de servicio de Atlas.

Ejemplo de formato de secreto de cliente de cuenta de servicio Atlas: mdb_sa_sk_<random-string>.

7

Si desea utilizar una ruta diferente para el archivo de configuración, introduzca la ruta donde desea guardar dicho archivo.

Por ejemplo, /Users/user.name/Library/Application Support/Code/User/mcp.json.

La utilidad crea el archivo de configuración. Lea las instrucciones sobre cómo usar el archivo de configuración con su cliente de IA. La utilidad también indica la ubicación del archivo de configuración.

Para obtener más detalles sobre cómo configurar el archivo, agregar ajustes adicionales o configurar manualmente un archivo, consulte la sección "Configuración manual de archivos del servidor MCP de MongoDB".

Reinicia tu cliente de IA para que utilice el archivo de configuración JSON que creaste o actualizaste en la sección anterior.

Una vez configurado el servidor MCP de MongoDB, podrá acceder al clúster de MongoDB desde su cliente de IA.

1

En su cliente de IA, compruebe que el servidor MCP de MongoDB esté en funcionamiento y asegúrese de que su lista de herramientas MCP incluya las herramientas MCP de MongoDB, si es posible.

2

Se deben ejecutar comandos en el cliente de IA para probar las herramientas del servidor MCP de MongoDB. Las respuestas exactas variarán según los datos en la implementación de MongoDB y el cliente y modelo de IA que se esté utilizando. Las siguientes muestras de comandos asumen que el servidor MCP tiene acceso tanto de lectura como de escritura a la implementación de MongoDB.

  1. Primero, crea una nueva base de datos y colección para trabajar ejecutando el siguiente comando:

    Create a new MongoDB collection named "products" and insert
    some sample data into the collection with the following fields:
    - name (string)
    - price (number)
    - category (string)
    - quantity (number)
    - inStock (boolean)
    I'll help you insert sample data into a MongoDB collection named "products" with the specified fields. Let me set this up for you.
    Ran `list-databases` - MongoDB (MCP Server)
    I'll create a sample database called "sample_store" and insert some product data into a "products" collection. Let's create the collection first:
    Ran `create-collection` - MongoDB (MCP Server)
    Now I'll insert sample product data into the "products" collection with all the required fields:
    Ran `insert-many` - MongoDB (MCP Server)
    Let's verify the data was inserted properly by querying the collection:
    Ran `find` - MongoDB (MCP Server)
    The sample data has been successfully inserted into the "products" collection. Here are some details of the inserted documents:
    Laptop:
    Price: $1,299.99
    Category: Electronics
    Quantity: 15
    InStock: true
    Smartphone:
    Price: $799.99
    Category: Electronics
    Quantity: 25
    InStock: true
    Headphones:
    Price: $149.99
    Category: Audio
    Quantity: 40
    InStock: true
    ...
  2. Ahora que existe una colección de MongoDB con algunos datos de muestra, se pueden ejecutar indicaciones para interactuar con la colección utilizando las herramientas de MCP:

Ejecuta los siguientes comandos en el cliente de IA para explorar y hacer una query a los datos en lenguaje natural:

Explain the schema of the "products" collection and provide a summary
of the data.
I'll help you explain the schema of the "products" collection and provide a summary of the data. Let me interact with your MongoDB database through the MCP server to get this information.
Ran `collection-schema` - MongoDB (MCP Server)
Now, let me fetch some sample data from the collection to provide you with a summary:
Ran `find` - MongoDB (MCP Server)
Let's also get a count of the total number of documents in the collection:
Ran `count` - MongoDB (MCP Server)
Let me get some aggregated statistics about the data:
Ran `aggregate` - MongoDB (MCP Server)
Ran `aggregate` - MongoDB (MCP Server)
Schema and Data Summary for the "products" Collection
Schema Overview
The "products" collection has the following schema:
1. _id: ObjectId - MongoDB's default unique identifier for each document
2. name: String - The name of the product
3. price: Number - The price of the product in USD
4. category: String - The category the product belongs to
5. quantity: Number - The available quantity of the product
6. inStock: Boolean - Flag indicating whether the product is in stock or not
Data Summary
Overall Statistics:
- Total number of products: 10
- Products in stock: 8
- Products out of stock: 2
- Categories Distribution:
- Electronics: 3 products (Laptop, Smartphone, Gaming Console)
- Audio: 2 products (Headphones, Bluetooth Speaker)
- Kitchen: 2 products (Coffee Maker, Blender)
- Furniture: 1 product (Office Chair)
- Home: 1 product (Desk Lamp)
- Wearables: 1 product (Fitness Tracker)
Price Range:
- Lowest priced item: $29.99 (Desk Lamp)
- Highest priced item: $1,299.99 (Laptop)
Inventory Status:
- Total inventory quantity: 153 items
- Average price across all products: approximately $313.99
- Products with zero quantity: 2 (Fitness Tracker, Blender) - these are marked as out of stock
Category Insights:
- Electronics has the highest average price at approximately $866.66
- Audio products have the highest total quantity (60 items)
- All zero-quantity products are correctly marked as out of stock (false)
This collection appears to be a simple product catalog for a store with various categories of merchandise, including pricing and inventory information
Find all products in the "products" collection that are out of stock
and update them to "in stock".
I'll help you find all products in the "products" collection that are out of stock and update them to be in stock. Let me interact with your MongoDB database through the MCP server to accomplish this.
First, let's find all products that are currently out of stock:
Ran `find` - MongoDB (MCP Server)
Now I'll update these out-of-stock products to be in stock. For this example, I'll also set a reasonable quantity value for each item:
Ran `update-many` - MongoDB (MCP Server)
Let's verify the updates by checking all products that were previously out of stock:
Ran `find` - MongoDB (MCP Server)
Great! I've successfully:
1. Found all products that were out of stock (2 products):
- Fitness Tracker (Wearables category)
- Blender (Kitchen category)
2. Updated these products to:
- Set them as in stock (inStock: true)
- Set their quantity to 10 units each
The update has been completed successfully, and both products are now marked as in stock with 10 units available for each. The MongoDB update operation matched 2 documents and modified 2 documents, confirming that all out-of-stock products have been updated as requested.

Si cuentas con un clúster de Atlas y se han activado las herramientas MCP específicas de Atlas, ejecuta los siguientes comandos en el cliente de IA para realizar algunas tareas administrativas:

List all my organizations, projects, and clusters in Atlas.
I'll help you list all your MongoDB Atlas organizations, projects, and clusters. Let me retrieve that information for you.
Ran `atlas-list-orgs` - MongoDB (MCP Server)
Now that I've found your organization, let me list all the projects under it.
Ran `atlas-list-projects` - MongoDB (MCP Server)
Now, let me list all the clusters across all your projects:
Ran `atlas-list-clusters` - MongoDB (MCP Server)
Let me get more detailed information about each of your clusters:
Ran `atlas-inspect-cluster` - MongoDB (MCP Server)
Summary of Your Atlas Resources
Organization
- MongoDB (ID: <your-org-id>)
Projects (2)
- Sample Project (ID: <proj-id-1>)
- Test Project (ID: <proj-id-2>)
Clusters (2)
1. Cluster0 (in Sample Project)
- Type: DEDICATED
- Tier: M20
- State: UPDATING
- MongoDB Version: 8.1.1
- Connection String: <connection-string-1>
2. Cluster1 (in Test Project)
- Type: FREE
- Tier: N/A
- State: IDLE
- MongoDB Version: 8.0.10
- Connection String: <connection-string-2>
Create a new database user with read-only access to the "products"
collection, then add my current IP address to my cluster's access list.
I'll help you create a new database user with read-only access to the "products" collection and add your current IP address to your cluster's access list. Let me do this step-by-step.
Ran `atlas-list-orgs` - MongoDB (MCP Server)
First, I need to get information about your available Atlas projects to determine where to create the database user.
Ran `atlas-list-projects` - MongoDB (MCP Server)
Now, let's check which clusters are available:
Ran `atlas-list-clusters` - MongoDB (MCP Server)
Let's create a new database user with read-only access to the "products" collection in the Project with the Cluster. I'll create a user named "products_readonly":
Ran `atlas-create-db-user` - MongoDB (MCP Server)
Great! Now let's add your current IP address to the cluster's access list:
Ran `atlas-create-access-list` - MongoDB (MCP Server)
Let's verify the IP was added by checking the access list:
Ran `atlas-inspect-access-list` - MongoDB (MCP Server)
Perfect! Now let's also verify the user was created by listing all database users:
Ran `atlas-list-db-users` - MongoDB (MCP Server)
Summary of Actions Completed
1. Created a new database user:
- Username: products_readonly
- Password: <generated-password> (save this in a secure location)
- Access: Read-only access to the "products" collection in the "sample_store" database
- Project: Project (ID: <proj-id>)
- Cluster: Sample Cluster
2. Added your current IP address to the cluster's access list:
- IP Address: <your-ip-address>
- Project: Sample Project (ID: <proj-id>)
- Comment: "Added for products_readonly user"
The new user can now connect to your Atlas cluster and read data from the "products" collection, but cannot modify it. Your IP address has been added to the access list, allowing you to connect to the cluster from your current location.

Ejecuta el siguiente comando para generar código relacionado con los datos de MongoDB. Proporcionar contexto, como esquemas y estructuras de datos, permite una generación de código más precisa, así como reducir errores de interpretación y mejorar las capacidades de los agentes.

Review the schema of the "products" collection, then generate a Javascript
function that updates the "inStock" field to `false` when a product
reaches a quantity of 0.
I'll first review the schema of the "products" collection to understand its structure, then generate a Javascript function to update the "inStock" field to false when a product reaches a quantity of 0.
Ran `collection-schema` - MongoDB (MCP Server)
Now let me get some sample data from the collection to better understand the current state of the documents:
Ran `find` - MongoDB (MCP Server)
Based on the schema and sample data, I'll now generate a Javascript function that:
- Monitors the products collection
- Updates the "inStock" field to false when a product's quantity reaches 0
- Provides appropriate error handling and logging
Here's the Javascript function:
```
/**
* Updates the inStock field to false when a product's quantity reaches 0
*
* This function can be used in two ways:
* 1. As a one-time update to sync all products (updateAllProducts)
* 2. As an automated trigger after any update operation (setupUpdateTrigger)
*
* @param {Object} client - MongoDB client instance
* @param {string} dbName - Database name (default: 'sample_store')
* @param {string} collectionName - Collection name (default: 'products')
* @returns {Promise} Promise that resolves when the operation completes
*/
async function updateProductStockStatus(client, dbName = 'sample_store', collectionName = 'products') {
try {
// Get reference to the database and collection
const db = client.db(dbName);
const collection = db.collection(collectionName);
// Find all products with quantity 0 but still marked as in stock
const result = await collection.updateMany(
{ quantity: 0, inStock: true },
{ $set: { inStock: false } }
);
console.log(`Updated ${result.modifiedCount} products to out of stock`);
return result;
} catch (err) {
console.error('Error updating product stock status:', err);
throw err;
}
}
/**
* Sets up a change stream to automatically update inStock status
* when quantity changes to 0
*
* @param {Object} client - MongoDB client instance
* @param {string} dbName - Database name (default: 'sample_store')
* @param {string} collectionName - Collection name (default: 'products')
* @returns {ChangeStream} The change stream object
*/
async function setupUpdateTrigger(client, dbName = 'sample_store', collectionName = 'products') {
... (truncated)

Si hay problemas con la configuración del servidor MCP, se debe consultar Solución de problemas del servidor MCP de MongoDB.

Para conocer las opciones completas de configuración y las herramientas disponibles, consulta Configurar el servidor MCP y las conexiones y Herramientas Compatibles.

Para obtener más ejemplos de uso, consulta Ejemplos de uso del servidor MCP de MongoDB.

Volver

Overview