Skip to main content
Glama
CaptainCrouton89

MCP Server Boilerplate

mongo-count-documents

Count documents in a MongoDB collection using a query filter to get precise document totals for data analysis and monitoring.

Instructions

Count documents in a MongoDB collection

Input Schema

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

Implementation Reference

  • The main handler function for the 'mongo-count-documents' tool. It ensures a connection to the specified MongoDB database, retrieves the collection, counts the documents matching the optional filter using countDocuments(), and returns a text response with the count.
    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 input schema defining parameters: database (string), collection (string), and optional filter (JSON 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 using server.tool(), including name, description, schema, and 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'}`);
        }
      }
    );
  • Helper function to ensure MongoDB client connection and database instance are available, used by the tool handler.
    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)!;

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/CaptainCrouton89/mongo-mcp'

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