count
Count documents in a MongoDB collection using db.collection.count() with optional query filters to tally specific records.
Instructions
Gets the number of documents in a MongoDB collection using db.collection.count() and query as an optional filter parameter
Input 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:27-53 (handler)The execute method of the CountTool class implements the logic to count documents in a MongoDB collection, optionally checking index usage and returning the 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-14 (schema)Zod schema defining the input arguments for the count tool, specifically the optional query filter.
export const CountArgs = { query: z .record(z.string(), z.unknown()) .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:22-43 (registration)The CountTool is registered (included) in the MongoDbTools array which lists all MongoDB tools.
export const MongoDbTools = [ ConnectTool, ListCollectionsTool, ListDatabasesTool, CollectionIndexesTool, CreateIndexTool, CollectionSchemaTool, FindTool, InsertManyTool, DeleteManyTool, CollectionStorageSizeTool, CountTool, DbStatsTool, AggregateTool, UpdateManyTool, RenameCollectionTool, DropDatabaseTool, DropCollectionTool, ExplainTool, CreateCollectionTool, LogsTool, ]; - src/tools/mongodb/tools.ts:11-11 (registration)Import statement for the CountTool in the MongoDB tools registration file.
import { CountTool } from "./read/count.js";