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.
Input Schema
TableJSON 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 }], }; } } );