Skip to main content
Glama
jonfreeland

MongoDB MCP Server

by jonfreeland

count_documents

Count documents in a MongoDB collection that match specific criteria to understand data volume and optimize queries without retrieving full documents.

Instructions

Count documents in a collection that match a filter.

Benefits:

  • More efficient than retrieving full documents

  • Good for understanding data volume

  • Can help planning query strategies

  • Optimize pagination implementation

Example: use_mcp_tool with server_name: "mongodb", tool_name: "count_documents", arguments: { "collection": "users", "filter": { "active": true, "age": { "$gte": 21 } } }

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseNoDatabase name (optional if default database is configured)
collectionYesCollection name
filterNoMongoDB query filter (optional, defaults to count all documents)

Implementation Reference

  • Handler for the count_documents tool. Extracts parameters, connects to the MongoDB database, executes countDocuments(filter) on the specified collection, and returns the count in JSON format.
    case 'count_documents': {
      const { database, collection, filter = {} } = request.params.arguments as {
        database?: string;
        collection: string;
        filter?: object;
      };
      const dbName = database || this.defaultDatabase;
      if (!dbName) {
        throw new McpError(
          ErrorCode.InvalidRequest,
          'Database name is required when no default database is configured'
        );
      }
      
      const db = client.db(dbName);
      const count = await db.collection(collection).countDocuments(filter);
      
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify({ count }, null, 2),
          },
        ],
      };
    }
  • src/index.ts:757-792 (registration)
    Tool registration entry for count_documents, defining its name, description, and input schema for the ListToolsRequestSchema handler.
              name: 'count_documents',
              description: `Count documents in a collection that match a filter.
      
    Benefits:
    - More efficient than retrieving full documents
    - Good for understanding data volume
    - Can help planning query strategies
    - Optimize pagination implementation
    
    Example:
    use_mcp_tool with
      server_name: "mongodb",
      tool_name: "count_documents",
      arguments: {
        "collection": "users",
        "filter": { "active": true, "age": { "$gte": 21 } }
      }`,
              inputSchema: {
                type: 'object',
                properties: {
                  database: {
                    type: 'string',
                    description: 'Database name (optional if default database is configured)',
                  },
                  collection: {
                    type: 'string',
                    description: 'Collection name',
                  },
                  filter: {
                    type: 'object',
                    description: 'MongoDB query filter (optional, defaults to count all documents)',
                  },
                },
                required: ['collection'],
              },
            },
  • Input schema definition for the count_documents tool, specifying parameters: database (optional), collection (required), and filter (optional).
    inputSchema: {
      type: 'object',
      properties: {
        database: {
          type: 'string',
          description: 'Database name (optional if default database is configured)',
        },
        collection: {
          type: 'string',
          description: 'Collection name',
        },
        filter: {
          type: 'object',
          description: 'MongoDB query filter (optional, defaults to count all documents)',
        },
      },
      required: ['collection'],
    },
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It adds useful behavioral context about efficiency benefits and optimization use cases, but does not disclose critical details like performance characteristics, error handling, or authentication requirements. The example helps illustrate usage but doesn't fully compensate for the lack of annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with a clear purpose statement, bullet-pointed benefits, and a practical example. It is appropriately sized and front-loaded, though the benefits section could be slightly more concise as some points overlap (e.g., 'Good for understanding data volume' and 'Can help planning query strategies').

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations and no output schema, the description provides adequate context for a read-only counting tool with good schema coverage. It covers purpose, benefits, and usage example, but lacks details on return format, error cases, or performance limits, which would be helpful for a tool with behavioral implications like database queries.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all three parameters thoroughly. The description does not add any parameter-specific semantics beyond what's in the schema, such as explaining filter syntax or default behaviors, though the example implicitly shows filter usage. Baseline 3 is appropriate when schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Count documents in a collection that match a filter.' It specifies the verb ('count'), resource ('documents in a collection'), and scope ('match a filter'), but does not explicitly differentiate it from sibling tools like 'query' or 'aggregate' that might also involve counting.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context for when to use this tool through the 'Benefits' section, highlighting efficiency over retrieving full documents and use cases like data volume understanding and pagination planning. However, it does not explicitly state when not to use it or name specific alternatives among sibling tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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/jonfreeland/mongodb-mcp'

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