MongoDBAtlasDocumentStore: DuplicatePolicy.FAIL / NONE never raises, duplicate IDs are inserted (store does not create a unique index on `id`)

Open
#4,265 2 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
Half a day
Newbie friendliness
74/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
mongodb, python
Domain
databases

Research direction

Start in integrations/mongodb_atlas/src/haystack_integrations/document_stores/mongodb_atlas/document_store.py at the FAIL branches (lines 738, 785) and _ensure_connection_setup/_ensure_connection_setup_async; AzureDocumentDBDocumentStore._ensure_connection_setup already does the index creation. tests/conftest.py line 70 adds the unique index by hand, masking the bug—run the mongodb_atlas tests without it. Done when both setup paths create the unique id index, the docstring notes it, and a test expects DuplicateDocumentError on a repeated id; the pre-existing-duplicates question needs a maintainer decision.

Written by the indexing model from the issue text.

Description

integration:mongodb-atlas P2

Describe the bug

MongoDBAtlasDocumentStore.write_documents does not enforce DuplicatePolicy.FAIL (or NONE, which it maps to FAIL). Writing a document whose ID is already stored inserts a second copy instead of raising DuplicateDocumentError. Re-running an indexing pipeline with the default DocumentWriter duplicates every document.

Cause

At 8249f30, in integrations/mongodb_atlas/src/haystack_integrations/document_stores/mongodb_atlas/document_store.py, the FAIL branch issues plain InsertOne operations (line 738, async line 785) and relies on MongoDB rejecting them. Documents are keyed by the id field, not _id, so MongoDB only rejects the insert if the collection has a unique index on id.

The store never creates that index, and neither the class docstring nor the init parameters mention that one is needed. The test suite passes because tests/conftest.py (line 70) creates it by hand: database[collection_name].create_index("id", unique=True).

AzureDocumentDBDocumentStore in this repo, which uses the same write logic, creates the index itself in _ensure_connection_setup.

To Reproduce

Against mongodb/mongodb-atlas-local, on a collection created with create_collection only:

import os
from uuid import uuid4
from haystack import Document
from haystack.components.writers import DocumentWriter
from haystack.document_stores.types import DuplicatePolicy
from haystack_integrations.document_stores.mongodb_atlas import MongoDBAtlasDocumentStore
from pymongo import MongoClient

DB, COLLECTION = "haystack_repro", "docs_" + uuid4().hex[:8]
client = MongoClient(os.environ["MONGO_CONNECTION_STRING"])
client[DB].create_collection(COLLECTION)

store = MongoDBAtlasDocumentStore(database_name=DB, collection_name=COLLECTION,
                                  vector_search_index="unused", full_text_search_index="unused")
doc = Document(id="A", content="original")

for label, write in [
    ("write_documents(policy=FAIL)", lambda: store.write_documents([doc], policy=DuplicatePolicy.FAIL)),
    ("write_documents() default", lambda: store.write_documents([doc])),
    ("DocumentWriter default", lambda: DocumentWriter(document_store=store).run(documents=[doc])),
]:
    try:
        write(); result = "no error"
    except Exception as e:
        result = "RAISE " + type(e).__name__
    print(f"{label:30} -> {result:12} count_documents={store.count_documents()}")
print("stored ids:", [d["id"] for d in client[DB][COLLECTION].find()])

Output:

write_documents(policy=FAIL)   -> no error    count_documents=1
write_documents() default      -> no error    count_documents=2
DocumentWriter default         -> no error    count_documents=3
stored ids: ['A', 'A', 'A']

Expected: the second and third writes raise DuplicateDocumentError and the count stays at 1.

Suggested fix

Create the unique index on id in _ensure_connection_setup and _ensure_connection_setup_async, as AzureDocumentDBDocumentStore does, and document it. One open question: on an existing collection that already contains duplicate IDs, create_index will fail. Should the store raise a DocumentStoreError explaining the problem, or log a warning and continue?

Happy to open a PR with tests once the direction is confirmed.

Describe your environment (please complete the following information):

  • OS: Windows 11 (NT 10.0.26200)
  • Haystack version: haystack-ai 3.5.0
  • Integration version: mongodb-atlas-haystack 5.0.0
  • pymongo: 4.20.0
  • MongoDB: mongodb/mongodb-atlas-local Docker image
  • Python: 3.13.15
Dominant language
Python
Stars
212
Forks
396
Avg merge
2d 9h
Merged PRs (30d)
95

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from deepset-ai/haystack-core-integrations

All issues in deepset-ai/haystack-core-integrations

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.