mongo-create-document
Insert JSON documents into MongoDB collections using this MCP server tool. Specify database, collection, and document data to create new records in your MongoDB database.
Instructions
Create a new document in a MongoDB collection
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| database | Yes | Database name | |
| collection | Yes | Collection name | |
| document | Yes | Document to insert as JSON object |
Implementation Reference
- src/index.ts:110-128 (handler)Handler function that connects to the MongoDB database, retrieves the collection, inserts the document using insertOne, and returns success message with inserted ID.async ({ database: dbName, collection: collectionName, document }) => { try { const db = await ensureConnection(dbName); const collection: Collection = db.collection(collectionName); const result = await collection.insertOne(document); return { content: [ { type: "text", text: `Document created successfully with ID: ${result.insertedId}`, }, ], }; } catch (error) { throw new Error(`Failed to create document: ${error instanceof Error ? error.message : 'Unknown error'}`); } }
- src/index.ts:105-109 (schema)Zod schema defining input parameters: database, collection, and document.{ database: z.string().describe("Database name"), collection: z.string().describe("Collection name"), document: z.record(z.any()).describe("Document to insert as JSON object"), },
- src/index.ts:102-129 (registration)Full registration of the mongo-create-document tool using McpServer.tool(), including name, description, schema, and inline handler.server.tool( "mongo-create-document", "Create a new document in a MongoDB collection", { database: z.string().describe("Database name"), collection: z.string().describe("Collection name"), document: z.record(z.any()).describe("Document to insert as JSON object"), }, async ({ database: dbName, collection: collectionName, document }) => { try { const db = await ensureConnection(dbName); const collection: Collection = db.collection(collectionName); const result = await collection.insertOne(document); return { content: [ { type: "text", text: `Document created successfully with ID: ${result.insertedId}`, }, ], }; } catch (error) { throw new Error(`Failed to create document: ${error instanceof Error ? error.message : 'Unknown error'}`); } } );
- src/index.ts:88-100 (helper)Helper function to ensure MongoDB client connection and retrieve or cache the database instance.async function ensureConnection(dbName: string): Promise<Db> { if (!mongoClient) { const uri = getMongoUri(); mongoClient = new MongoClient(uri); await mongoClient.connect(); } if (!databases.has(dbName)) { databases.set(dbName, mongoClient.db(dbName)); } return databases.get(dbName)!; }