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
| Name | Required | Description | Default |
|---|---|---|---|
| databaseName | Yes | Имя базы данных | |
| collectionName | Yes | Имя коллекции | |
| filter | No | JSON строка с фильтром для поиска (необязательно) | |
| limit | No | Максимальное количество документов (по умолчанию 100) |
Implementation Reference
- src/server.py:516-539 (handler)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()
- src/index.ts:778-819 (handler)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(); } }
- src/server.py:238-263 (schema)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"], }, },
- src/index.ts:251-276 (schema)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"], }, },