insertOne
Add a single document to a specified MongoDB collection through the MCP Database Server, enabling data insertion via natural language commands.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| collectionName | Yes | ||
| document | Yes |
Implementation Reference
- src/index.ts:103-122 (handler)The main execution logic for the 'insertOne' MCP tool: connects to MongoDB, gets the collection, calls insertOne(document), and returns success/error response.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)Zod input schema validation for the 'insertOne' tool parameters: collectionName (string) and document (any object).{ collectionName: z.string(), document: z.object({}), },
- src/index.ts:97-123 (registration)Registration of the 'insertOne' tool on the MCP server instance using the tool name, 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 }], }; } } );