{"record":{"id":"46c52f21ae12a933","repo":"microsoft/semantic-kernel","slug":"failed-to-search-the-collection-46c52f","errorCode":null,"errorMessage":"Failed to search the collection.","messagePattern":"Failed to search the collection\\.","errorType":"exception","errorClass":"VectorSearchExecutionException","httpStatus":null,"severity":"error","filePath":"python/semantic_kernel/connectors/mongodb.py","lineNumber":394,"sourceCode":"        }\n        if filter := self._build_filter(options.filter):\n            vector_search_query[\"filter\"] = filter if isinstance(filter, dict) else {\"$and\": filter}\n\n        projection_query: dict[str, int | dict] = {\n            field: 1\n            for field in self.definition.get_names(\n                include_vector_fields=options.include_vectors,\n                include_key_field=False,  # _id is always included\n            )\n        }\n        projection_query[MONGODB_SCORE_FIELD] = {\"$meta\": \"vectorSearchScore\"}\n        try:\n            raw_results = await collection.aggregate([\n                {\"$vectorSearch\": vector_search_query},\n                {\"$project\": projection_query},\n            ])\n        except Exception as exc:\n            raise VectorSearchExecutionException(\"Failed to search the collection.\") from exc\n        return KernelSearchResults(\n            results=self._get_vector_search_results_from_results(raw_results, options),\n            total_count=None,  # no way to get a count before looping through the result cursor\n        )\n\n    async def _inner_keyword_hybrid_search(\n        self,\n        options: VectorSearchOptions,\n        values: Any | None = None,\n        vector: Sequence[float | int] | None = None,\n        **kwargs: Any,\n    ) -> KernelSearchResults[VectorSearchResult[TModel]]:\n        collection = self._get_collection()\n        vector_field = self.definition.try_get_vector_field(options.vector_property_name)\n        if not vector_field:\n            raise VectorStoreModelException(\n                f\"Vector field '{options.vector_property_name}' not found in the data model definition.\"\n            )","sourceCodeStart":376,"sourceCodeEnd":412,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/connectors/mongodb.py#L376-L412","documentation":"Raised by MongoDBAtlasCollection._inner_vector_search (VectorSearchExecutionException, subclass of VectorStoreOperationException) wrapping ANY exception thrown while running the `$vectorSearch` + `$project` aggregation. The original error is chained as `__cause__`. Because the catch is broad (`except Exception`), the message alone is generic — you must inspect the cause to know whether the index is missing, dimensions mismatch, or the connection failed.","triggerScenarios":"The Atlas `$vectorSearch` aggregation fails: the named search index does not exist; index_name mismatch; queryVector dimensions != index numDimensions; the path field is not indexed; auth/network/timeout errors; Atlas tier/region issues; invalid filter expression from _build_filter.","commonSituations":"Vector search index not yet created in Atlas (or still building); index_name in code != index name in Atlas; embedding model changed dimensions without re-creating the index; wrong database/collection; expired credentials.","solutions":["Inspect the chained cause: `except VectorSearchExecutionException as e: log(e.__cause__)`.","Verify a vector search index named `index_name` exists on the collection in Atlas and is 'Active'.","Confirm queryVector length equals the index numDimensions and the 'path' matches the indexed field.","Check connectivity/credentials to the Atlas cluster."],"exampleFix":"// before\nres = await collection.search(search_type=SearchType.VECTOR, vector=emb)\n// after\ntry:\n    res = await collection.search(search_type=SearchType.VECTOR, vector=emb)\nexcept VectorSearchExecutionException as e:\n    raise RuntimeError(f'atlas vector search failed: {e.__cause__!r}') from e","handlingStrategy":"try-catch","validationCode":"# preflight: ensure a vector index exists with matching dimensions\n# (run in Atlas UI or via collection.ensure_index_exists if available)\n# then guard the query\nassert emb is not None and len(emb) == expected_dim, 'vector dim mismatch'","typeGuard":null,"tryCatchPattern":"from semantic_kernel.exceptions import VectorSearchExecutionException\ntry:\n    res = await collection.search(search_type=SearchType.VECTOR, vector=emb)\nexcept VectorSearchExecutionException as e:\n    cause = e.__cause__\n    if 'vectorSearch' in str(cause).lower() and 'index' in str(cause).lower():\n        await ensure_vector_index(collection)  # create/fix index, then retry once\n        res = await collection.search(search_type=SearchType.VECTOR, vector=emb)\n    else:\n        raise","preventionTips":["Always read e.__cause__ — the wrapper message is generic.","Create and wait for the Atlas vector search index (Active) before querying.","Keep embedding dimensions and the index numDimensions in sync; re-create index when the model changes.","Validate index_name and the indexed path field match your collection."],"tags":["mongodb","vector-store","search","execution-error","atlas-index"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}