count
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
| Name | Required | Description | Default |
|---|---|---|---|
| database | Yes | Database name | |
| collection | Yes | Collection 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 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", }, ], }; }
- src/tools/mongodb/read/count.ts:7-22 (schema)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, };
- src/tools/mongodb/tools.ts:11-11 (registration)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";
- src/tools/index.ts:8-10 (registration)Collects all MongoDB tools (including CountTool via MongoDbTools) into the AllTools array for registration with the MCP server....MongoDbTools, ...AtlasTools, ...AtlasLocalTools,