Skip to main content
Glama
mongodb-js

MongoDB MCP Server

Official
by mongodb-js

count

Read-only

Count documents in a MongoDB collection, optionally filtering results with a query parameter to get specific document totals.

Instructions

Gets the number of documents in a MongoDB collection using db.collection.count() and query as an optional filter parameter

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseYesDatabase name
collectionYesCollection name
queryNoA filter/query parameter. Allows users to filter the documents to count. Matches the syntax of the filter argument of db.collection.count().

Implementation Reference

  • The execute method implements the core logic of the 'count' tool: connects to the MongoDB provider, optionally checks index usage for the count operation, executes the count query, and returns a text result with the document count.
    protected async execute({ database, collection, query }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
        const provider = await this.ensureConnected();
    
        // Check if count operation uses an index if enabled
        if (this.config.indexCheck) {
            await checkIndexUsage(provider, database, collection, "count", async () => {
                return provider.runCommandWithCheck(database, {
                    explain: {
                        count: collection,
                        query,
                    },
                    verbosity: "queryPlanner",
                });
            });
        }
    
        const count = await provider.count(database, collection, query);
    
        return {
            content: [
                {
                    text: `Found ${count} documents in the collection "${collection}"`,
                    type: "text",
                },
            ],
        };
    }
  • Defines the input schema for the 'count' tool including the optional query filter (CountArgs), the tool name 'count', description, and combined argsShape inheriting from DbOperationArgs.
    export const CountArgs = {
        query: zEJSON()
            .optional()
            .describe(
                "A filter/query parameter. Allows users to filter the documents to count. Matches the syntax of the filter argument of db.collection.count()."
            ),
    };
    
    export class CountTool extends MongoDBToolBase {
        public name = "count";
        protected description =
            "Gets the number of documents in a MongoDB collection using db.collection.count() and query as an optional filter parameter";
        protected argsShape = {
            ...DbOperationArgs,
            ...CountArgs,
        };
  • Exports the CountTool class from its implementation file, making it available for inclusion in the collection of MongoDB tools.
    export { CountTool } from "./read/count.js";
  • Collects all MongoDB tools (including CountTool via MongoDbTools) into the AllTools array for registration with the MCP server.
    ...MongoDbTools,
    ...AtlasTools,
    ...AtlasLocalTools,
Behavior3/5

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

Annotations provide readOnlyHint=true and destructiveHint=false, indicating a safe read operation. The description adds value by specifying the MongoDB method used ('db.collection.count()') and that the query is optional, which gives context beyond annotations. However, it doesn't disclose additional behavioral traits like performance implications, rate limits, or error handling. No contradiction with annotations exists.

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

Conciseness5/5

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

The description is a single, efficient sentence that front-loads the core purpose and includes key details (MongoDB method and optional query). There is no wasted text, and it's appropriately sized for the tool's complexity. Every part of the sentence contributes to understanding the tool's function.

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 the tool's moderate complexity (3 parameters, nested object in query), annotations cover safety, and schema coverage is high, the description is adequate but has gaps. It lacks details on output (e.g., what the count returns, error cases) and doesn't fully address behavioral context like performance. For a read-only tool with good schema support, it meets minimum viability but could be more complete.

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%, with clear descriptions for 'database', 'collection', and 'query'. The description adds minimal semantics by noting the query is 'optional' and matches 'db.collection.count()' syntax, but this is largely redundant with the schema's details. Since schema coverage is high, the baseline score of 3 is appropriate, as the description doesn't significantly enhance parameter understanding.

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: 'Gets the number of documents in a MongoDB collection' with a specific verb ('Gets') and resource ('documents in a MongoDB collection'). It distinguishes from siblings like 'find' or 'aggregate' by focusing on counting rather than retrieving or processing documents. However, it doesn't explicitly differentiate from all siblings (e.g., 'db-stats' might also provide counts in a broader context).

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

Usage Guidelines3/5

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

The description implies usage by mentioning 'query as an optional filter parameter' for filtering documents, suggesting when to use it for filtered counts. However, it doesn't provide explicit guidance on when to choose this tool over alternatives like 'aggregate' for counting or other siblings, nor does it specify prerequisites or exclusions. The context is clear but lacks detailed alternatives.

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

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