insertOne
Add a single document to a specified MongoDB collection. Use this tool to insert new data records into your database through natural language commands.
Tool call template
Replace each placeholder with a value matching the input schema. Only required parameters are included; add optional parameters as needed.
{
"id": 1,
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"arguments": {
"collectionName": "<collectionName>",
"document": "<document>"
},
"name": "insertOne"
}
}Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| collectionName | Yes | ||
| document | Yes |
Implementation Reference
- src/index.ts:103-122 (handler)The handler function for the 'insertOne' MCP tool. It connects to the MongoDB database if necessary, retrieves the specified collection, inserts the provided document using collection.insertOne(), and returns a success or error message.
async ({ collectionName, document }) => { try { let db = mongodbConnection.getDb(); if (!db) { await mongodbConnection.connect(this.MONGODB_URI); db = mongodbConnection.getDb(); if (!db) throw new Error("Failed to connect to database"); } const collection = db.collection(collectionName); await collection.insertOne(document); return { content: [{ type: "text", text: "Document inserted successfully" }], }; } catch (error) { console.error(error); return { content: [{ type: "text", text: "Error: " + error }], }; } } - src/index.ts:99-102 (schema)The input schema for the 'insertOne' tool, defined using Zod. Requires 'collectionName' as string and 'document' as an object.
{ collectionName: z.string(), document: z.object({}), }, - src/index.ts:97-123 (registration)The registration of the 'insertOne' tool using this.mcpServer.tool(), including name, input schema, and handler function.
this.mcpServer.tool( "insertOne", { collectionName: z.string(), document: z.object({}), }, async ({ collectionName, document }) => { try { let db = mongodbConnection.getDb(); if (!db) { await mongodbConnection.connect(this.MONGODB_URI); db = mongodbConnection.getDb(); if (!db) throw new Error("Failed to connect to database"); } const collection = db.collection(collectionName); await collection.insertOne(document); return { content: [{ type: "text", text: "Document inserted successfully" }], }; } catch (error) { console.error(error); return { content: [{ type: "text", text: "Error: " + error }], }; } } );