find
Query specific documents from a MongoDB collection using filters, projections, sorting, and limit options to retrieve tailored data efficiently.
Instructions
Run a find query against a MongoDB collection
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| collection | Yes | Collection name | |
| database | Yes | Database name | |
| filter | No | The query filter, matching the syntax of the query argument of db.collection.find() | |
| limit | No | The maximum number of documents to return | |
| projection | No | The projection, matching the syntax of the projection argument of db.collection.find() | |
| sort | No | A document, describing the sort order, matching the syntax of the sort argument of cursor.sort(). The keys of the object are the fields to sort on, while the values are the sort directions (1 for ascending, -1 for descending). |
Implementation Reference
- src/tools/mongodb/read/find.ts:47-109 (handler)The execute method implementing the core logic of the 'find' tool: connects to MongoDB, runs the find query with limits and index checks, collects results up to byte limit, counts documents, and formats the response.protected async execute( { database, collection, filter, projection, limit, sort, responseBytesLimit }: ToolArgs<typeof this.argsShape>, { signal }: ToolExecutionContext ): Promise<CallToolResult> { let findCursor: FindCursor<unknown> | undefined = undefined; try { const provider = await this.ensureConnected(); // Check if find operation uses an index if enabled if (this.config.indexCheck) { await checkIndexUsage(provider, database, collection, "find", async () => { return provider .find(database, collection, filter, { projection, limit, sort }) .explain("queryPlanner"); }); } const limitOnFindCursor = this.getLimitForFindCursor(limit); findCursor = provider.find(database, collection, filter, { projection, limit: limitOnFindCursor.limit, sort, }); const [queryResultsCount, cursorResults] = await Promise.all([ operationWithFallback( () => provider.countDocuments(database, collection, filter, { // We should be counting documents that the original // query would have yielded which is why we don't // use `limitOnFindCursor` calculated above, only // the limit provided to the tool. limit, maxTimeMS: QUERY_COUNT_MAX_TIME_MS_CAP, }), undefined ), collectCursorUntilMaxBytesLimit({ cursor: findCursor, configuredMaxBytesPerQuery: this.config.maxBytesPerQuery, toolResponseBytesLimit: responseBytesLimit, abortSignal: signal, }), ]); return { content: formatUntrustedData( this.generateMessage({ collection, queryResultsCount, documents: cursorResults.documents, appliedLimits: [limitOnFindCursor.cappedBy, cursorResults.cappedBy].filter((limit) => !!limit), }), ...(cursorResults.documents.length > 0 ? [EJSON.stringify(cursorResults.documents)] : []) ), }; } finally { if (findCursor) { void this.safeCloseCursor(findCursor); } } }
- src/tools/mongodb/read/find.ts:15-36 (schema)Zod schema definition for the input arguments of the 'find' tool (FindArgs), including filter, projection, limit, sort, and responseBytesLimit.export const FindArgs = { filter: zEJSON() .optional() .describe("The query filter, matching the syntax of the query argument of db.collection.find()"), projection: z .object({}) .passthrough() .optional() .describe("The projection, matching the syntax of the projection argument of db.collection.find()"), limit: z.number().optional().default(10).describe("The maximum number of documents to return"), sort: z .object({}) .catchall(z.custom<SortDirection>()) .optional() .describe( "A document, describing the sort order, matching the syntax of the sort argument of cursor.sort(). The keys of the object are the fields to sort on, while the values are the sort directions (1 for ascending, -1 for descending)." ), responseBytesLimit: z.number().optional().default(ONE_MB).describe(`\ The maximum number of bytes to return in the response. This value is capped by the server's configured maxBytesPerQuery and cannot be exceeded. \ Note to LLM: If the entire query result is required, use the "export" tool instead of increasing this limit.\ `), };
- src/tools/mongodb/tools.ts:7-7 (registration)Export of the FindTool class from the MongoDB tools module.export { FindTool } from "./read/find.js";
- src/tools/index.ts:7-11 (registration)Collection of all tools including FindTool (via MongoDbTools) into AllTools array for server registration.export const AllTools: ToolClass[] = Object.values({ ...MongoDbTools, ...AtlasTools, ...AtlasLocalTools, });
- src/tools/mongodb/read/find.ts:41-44 (schema)Tool's argsShape combining DbOperationArgs and FindArgs for input validation.protected argsShape = { ...DbOperationArgs, ...FindArgs, };