Skip to main content
Glama
ricleedo

MCP Server Boilerplate

by ricleedo

mongo-count-documents

Count documents in a MongoDB collection using a query filter to retrieve specific data counts from your database.

Instructions

Count documents in a MongoDB collection

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseYesDatabase name
collectionYesCollection name
filterNoQuery filter as JSON object (optional)

Implementation Reference

  • Handler function that ensures database connection, retrieves the collection, counts documents matching the optional filter using countDocuments, and returns the count in a text response.
    async ({ database: dbName, collection: collectionName, filter = {} }) => { try { const db = await ensureConnection(dbName); const collection: Collection = db.collection(collectionName); const count = await collection.countDocuments(filter); return { content: [ { type: "text", text: `Found ${count} document(s) matching the filter`, }, ], }; } catch (error) { throw new Error(`Failed to count documents: ${error instanceof Error ? error.message : 'Unknown error'}`); } }
  • Zod schema defining input parameters: database name, collection name, and optional filter object.
    { database: z.string().describe("Database name"), collection: z.string().describe("Collection name"), filter: z.record(z.any()).optional().describe("Query filter as JSON object (optional)"), },
  • src/index.ts:264-291 (registration)
    Registration of the 'mongo-count-documents' tool with the MCP server, including description, input schema, and inline handler function.
    server.tool( "mongo-count-documents", "Count documents in a MongoDB collection", { database: z.string().describe("Database name"), collection: z.string().describe("Collection name"), filter: z.record(z.any()).optional().describe("Query filter as JSON object (optional)"), }, async ({ database: dbName, collection: collectionName, filter = {} }) => { try { const db = await ensureConnection(dbName); const collection: Collection = db.collection(collectionName); const count = await collection.countDocuments(filter); return { content: [ { type: "text", text: `Found ${count} document(s) matching the filter`, }, ], }; } catch (error) { throw new Error(`Failed to count documents: ${error instanceof Error ? error.message : 'Unknown error'}`); } } );

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ricleedo/mongo-boilerplate-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server