mongo-aggregate
Execute aggregation pipelines on MongoDB collections to process and analyze data through multiple transformation stages.
Instructions
Execute aggregation pipeline on a MongoDB collection
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| collection | Yes | Collection name | |
| database | Yes | Database name | |
| pipeline | Yes | Aggregation pipeline as array of stage objects |
Implementation Reference
- src/index.ts:241-261 (handler)The handler function for the 'mongo-aggregate' tool. It connects to the specified MongoDB database, retrieves the collection, executes the provided aggregation pipeline, formats the results, and returns them as a text content block.async ({ database: dbName, collection: collectionName, pipeline }) => { try { const db = await ensureConnection(dbName); const collection: Collection = db.collection(collectionName); const documents = await collection.aggregate(pipeline).toArray(); const formattedOutput = formatJsonOutput(documents); return { content: [ { type: "text", text: `Aggregation returned ${documents.length} document(s):\n\n${formattedOutput}`, }, ], }; } catch (error) { throw new Error(`Failed to execute aggregation: ${error instanceof Error ? error.message : 'Unknown error'}`); } }
- src/index.ts:236-240 (schema)The input schema for the 'mongo-aggregate' tool using Zod, defining parameters: database, collection, and pipeline.{ database: z.string().describe("Database name"), collection: z.string().describe("Collection name"), pipeline: z.array(z.record(z.any())).describe("Aggregation pipeline as array of stage objects"), },
- src/index.ts:233-262 (registration)The registration of the 'mongo-aggregate' tool using server.tool(), including name, description, schema, and handler function.server.tool( "mongo-aggregate", "Execute aggregation pipeline on a MongoDB collection", { database: z.string().describe("Database name"), collection: z.string().describe("Collection name"), pipeline: z.array(z.record(z.any())).describe("Aggregation pipeline as array of stage objects"), }, async ({ database: dbName, collection: collectionName, pipeline }) => { try { const db = await ensureConnection(dbName); const collection: Collection = db.collection(collectionName); const documents = await collection.aggregate(pipeline).toArray(); const formattedOutput = formatJsonOutput(documents); return { content: [ { type: "text", text: `Aggregation returned ${documents.length} document(s):\n\n${formattedOutput}`, }, ], }; } catch (error) { throw new Error(`Failed to execute aggregation: ${error instanceof Error ? error.message : 'Unknown error'}`); } } );