Skip to content

Build and run agents you can see, understand and trust.

fix(rag): preserve literal metadata values in MongoDB listings (#3591)

Jackp0t300398e3108a
diff --git a/src/agentscope/rag/_vdb/_mongodb.py b/src/agentscope/rag/_vdb/_mongodb.py
index 450b9bc8e..eb99aab99 100644
--- a/src/agentscope/rag/_vdb/_mongodb.py
+++ b/src/agentscope/rag/_vdb/_mongodb.py
@@ -440,6 +440,7 @@ class MongoDBStore(VectorStoreBase):
metadata_filter (`dict[str, Any] | None`, optional):
If provided, restrict aggregation to records whose
``chunk.metadata`` matches every ``key == value`` pair.
+ Values are matched literally, including dictionaries.
Returns:
`list[DocumentSummary]`:
@@ -450,7 +451,7 @@ class MongoDBStore(VectorStoreBase):
pipeline.append(
{
"$match": {
- f"chunk.metadata.{key}": value
+ f"chunk.metadata.{key}": {"$eq": value}
for key, value in metadata_filter.items()
},
},
@@ -508,6 +509,7 @@ class MongoDBStore(VectorStoreBase):
Maximum number of chunks to return.
metadata_filter (`dict[str, Any] | None`, optional):
Extra ``chunk.metadata`` equality constraints.
+ Values are matched literally, including dictionaries.
Returns:
`list[Chunk]`:
@@ -517,7 +519,7 @@ class MongoDBStore(VectorStoreBase):
return []
query: dict[str, Any] = {"document_id": document_id}
for key, value in (metadata_filter or {}).items():
- query[f"chunk.metadata.{key}"] = value
+ query[f"chunk.metadata.{key}"] = {"$eq": value}
cursor = (
self._col(collection)
diff --git a/tests/rag_vdb_mongodb_test.py b/tests/rag_vdb_mongodb_test.py
index 904726135..c3f1fa4cb 100644
--- a/tests/rag_vdb_mongodb_test.py
+++ b/tests/rag_vdb_mongodb_test.py
@@ -8,7 +8,7 @@ from contextlib import AsyncExitStack
from types import SimpleNamespace
from typing import Any
from unittest.async_case import IsolatedAsyncioTestCase
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, Mock, patch
from utils import AnyString
@@ -160,7 +160,12 @@ class _FakeMongoCollection:
doc
for doc in self._docs.values()
if all(
- _read_dotted(doc, key) == value
+ _read_dotted(doc, key)
+ == (
+ value["$eq"]
+ if isinstance(value, dict) and "$eq" in value
+ else value
+ )
for key, value in filter_doc.items()
)
]
@@ -252,6 +257,8 @@ class _FakeMongoCollection:
match: dict[str, Any],
) -> bool:
for key, expected in match.items():
+ if isinstance(expected, dict) and "$eq" in expected:
+ expected = expected["$eq"]
value = doc
for part in key.split("."):
value = value[part]
@@ -507,6 +514,57 @@ class MongoDBStoreTest(IsolatedAsyncioTestCase):
{"document_id": "doc"},
)
+ async def test_list_documents_uses_literal_metadata_values(self) -> None:
+ """Operator-shaped values must remain equality operands."""
+ collection = SimpleNamespace(
+ aggregate=AsyncMock(return_value=_FakeAsyncIterator([])),
+ )
+ with patch.object(self.store, "_col", return_value=collection):
+ await self.store.list_documents(
+ "shared",
+ metadata_filter={
+ "scope": {"$ne": "alpha"},
+ "label": {"$regex": "^private"},
+ "archived": None,
+ },
+ )
+ pipeline = collection.aggregate.call_args.args[0]
+ self.assertEqual(
+ pipeline[0],
+ {
+ "$match": {
+ "chunk.metadata.scope": {"$eq": {"$ne": "alpha"}},
+ "chunk.metadata.label": {"$eq": {"$regex": "^private"}},
+ "chunk.metadata.archived": {"$eq": None},
+ },
+ },
+ )
+
+ async def test_list_chunks_uses_literal_metadata_values(self) -> None:
+ """Listing keeps literal equality alongside the document fence."""
+ collection = SimpleNamespace(
+ find=Mock(return_value=_FakeFindCursor([])),
+ )
+ with patch.object(self.store, "_col", return_value=collection):
+ await self.store.list_chunks(
+ "shared",
+ "doc",
+ metadata_filter={
+ "scope": {"$ne": "alpha"},
+ "label": {"$regex": "^private"},
+ "archived": None,
+ },
+ )
+ self.assertEqual(
+ collection.find.call_args.args[0],
+ {
+ "document_id": "doc",
+ "chunk.metadata.scope": {"$eq": {"$ne": "alpha"}},
+ "chunk.metadata.label": {"$eq": {"$regex": "^private"}},
+ "chunk.metadata.archived": {"$eq": None},
+ },
+ )
+
async def test_search_candidate_limits(self) -> None:
"""Search caps candidates while preserving the requested limit."""
await self.store.create_collection("kb-1", dimensions=3)