Skip to main content
Glama

mongodb_find_documents

Search and retrieve documents from MongoDB collections by specifying database, collection, and optional filters to locate specific data entries.

Instructions

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

Input Schema

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

Implementation Reference

  • Python handler function that connects to MongoDB using pymongo, parses optional filter JSON, finds documents with limit, converts _id to string, and returns formatted JSON result.
    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()
  • TypeScript handler method that connects to MongoDB using mongodb driver, parses optional filter JSON, finds documents with limit, converts _id to string, and returns MCP content response.
    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 in the Python MCP server, defining parameters and validation.
    { "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"], }, },
  • Input schema definition for the mongodb_find_documents tool in the TypeScript MCP server, defining parameters and validation.
    { 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"], }, },

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