Skip to main content
Glama

mongodb_find_documents

Search and retrieve documents from MongoDB collections using filters and limits to find specific data.

Instructions

Находит документы в коллекции

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseNameYesИмя базы данных
collectionNameYesИмя коллекции
filterNoJSON строка с фильтром для поиска (необязательно)
limitNoМаксимальное количество документов (по умолчанию 100)

Implementation Reference

  • The primary handler function for the 'mongodb_find_documents' tool. Connects to MongoDB, parses optional filter JSON, queries the specified collection with limit, converts ObjectIds to strings, and returns formatted results as MCP content.
    private async mongodbFindDocuments( databaseName: string, collectionName: string, filterJson?: string, limit: number = 100 ) { const client = await this.getMongoClient(); try { const db = client.db(databaseName); const collection = db.collection(collectionName); const filter = filterJson ? JSON.parse(filterJson) : {}; const documents = await collection .find(filter) .limit(limit) .toArray(); // Преобразуем ObjectId в строки для JSON const documentsStr = JSON.stringify( documents.map((doc) => ({ ...doc, _id: doc._id.toString(), })), null, 2 ); return { content: [ { type: "text", text: `Найдено документов: ${documents.length}\n\n${documentsStr}`, }, ], }; } catch (error) { throw new Error( `Ошибка поиска документов: ${error instanceof Error ? error.message : String(error)}` ); } finally { await client.close(); } }
  • Input schema definition for the 'mongodb_find_documents' tool, registered in the listTools response.
    name: "mongodb_find_documents", description: "Находит документы в коллекции", inputSchema: { type: "object", properties: { databaseName: { type: "string", description: "Имя базы данных", }, collectionName: { type: "string", description: "Имя коллекции", }, filter: { type: "string", description: "JSON строка с фильтром для поиска (необязательно)", }, limit: { type: "number", description: "Максимальное количество документов (по умолчанию 100)", }, }, required: ["databaseName", "collectionName"], },
  • src/index.ts:366-372 (registration)
    Registration/dispatch of the 'mongodb_find_documents' handler in the CallToolRequest switch statement.
    case "mongodb_find_documents": return await this.mongodbFindDocuments( args?.databaseName as string, args?.collectionName as string, args?.filter as string | undefined, args?.limit as number | undefined );
  • Handler function for 'mongodb_find_documents' in the Python version of the server (note: dispatch is commented out, so not active). Similar logic to TS version.
    def mongodb_find_documents( database_name: str, collection_name: str, filter_json: Optional[str] = None, limit: int = 100, ) -> str: """Finds documents in collection""" client = MongoClient(MONGODB_URI) try: db = client[database_name] collection = db[collection_name] filter_dict = json.loads(filter_json) if filter_json else {} documents = list(collection.find(filter_dict).limit(limit)) # Convert ObjectId to strings for doc in documents: if "_id" in doc: doc["_id"] = str(doc["_id"]) documents_str = json.dumps(documents, ensure_ascii=False, indent=2) return f"Found documents: {len(documents)}\n\n{documents_str}" except Exception as e: raise Exception(f"Error finding documents: {str(e)}") finally: client.close()
  • Input schema for 'mongodb_find_documents' in the Python server's tool list.
    "name": "mongodb_find_documents", "description": "Finds documents in collection", "inputSchema": { "type": "object", "properties": { "databaseName": { "type": "string", "description": "Database name", }, "collectionName": { "type": "string", "description": "Collection name", }, "filter": { "type": "string", "description": "JSON string with search filter (optional)", }, "limit": { "type": "number", "description": "Maximum number of documents (default 100)", }, }, "required": ["databaseName", "collectionName"], },

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/TrueOleg/MCP-expirements'

If you have feedback or need assistance with the MCP directory API, please join our Discord server