Skip to main content
Glama
mongodb-js

MongoDB MCP Server

Official
by mongodb-js

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
NameRequiredDescriptionDefault
collectionYesCollection name
databaseYesDatabase name
filterNoThe query filter, matching the syntax of the query argument of db.collection.find()
limitNoThe maximum number of documents to return
projectionNoThe projection, matching the syntax of the projection argument of db.collection.find()
sortNoA 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

  • 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); } } }
  • 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.\ `), };
  • Export of the FindTool class from the MongoDB tools module.
    export { FindTool } from "./read/find.js";
  • Collection of all tools including FindTool (via MongoDbTools) into AllTools array for server registration.
    export const AllTools: ToolClass[] = Object.values({ ...MongoDbTools, ...AtlasTools, ...AtlasLocalTools, });
  • Tool's argsShape combining DbOperationArgs and FindArgs for input validation.
    protected argsShape = { ...DbOperationArgs, ...FindArgs, };

Other Tools

Related 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