count
Retrieve the total number of documents in a MongoDB collection, with an optional query parameter to filter and count specific documents based on defined criteria.
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
| Name | Required | Description | Default |
|---|---|---|---|
| collection | Yes | Collection name | |
| database | Yes | Database name | |
| query | No | A filter/query parameter. Allows users to filter the documents to count. Matches the syntax of the filter argument of db.collection.count(). |
Implementation Reference
- src/tools/mongodb/read/count.ts:26-52 (handler)The execute method implementing the count tool: ensures connection, optionally checks index usage for the count operation, executes provider.count, and formats the result.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", }, ], }; }
- src/tools/mongodb/read/count.ts:7-13 (schema)Input schema for the count tool defining the optional query filter parameter.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()." ), };
- src/tools/mongodb/tools.ts:11-11 (registration)Exports the CountTool class from the MongoDB read tools module.export { CountTool } from "./read/count.js";
- src/tools/index.ts:3-11 (registration)Imports MongoDB tools (including CountTool) and includes them in the AllTools array used by the server to register all tools.import * as MongoDbTools from "./mongodb/tools.js"; import type { ToolClass } from "./tool.js"; // Export the collection of tools for easier reference export const AllTools: ToolClass[] = Object.values({ ...MongoDbTools, ...AtlasTools, ...AtlasLocalTools, });
- CountTool class definition including name, description, argsShape composition, and operationType.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, }; static operationType: OperationType = "read";