{"record":{"id":"f73e2cdfbf40bb06","repo":"apache/beam","slug":"empty-mongodb-collection","errorCode":null,"errorMessage":"Empty Mongodb collection","messagePattern":"Empty Mongodb collection","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"sdks/python/apache_beam/io/mongodbio.py","lineNumber":564,"sourceCode":"          # https://docs.mongodb.com/manual/reference/operator/query/and/\n          \"$and\": [self.filter.copy(), id_filter]\n      }\n    else:\n      all_filters = id_filter\n\n    return all_filters\n\n  def _get_head_document_id(self, sort_order):\n    with MongoClient(self.uri, **self.spec) as client:\n      cursor = (\n          client[self.db][self.coll].find(filter={}, projection=[]).sort([\n              (\"_id\", sort_order)\n          ]).limit(1))\n      try:\n        return cursor[0][\"_id\"]\n\n      except IndexError:\n        raise ValueError(\"Empty Mongodb collection\")\n\n  def _replace_none_positions(self, start_position, stop_position):\n\n    if start_position is None:\n      start_position = self._get_head_document_id(ASCENDING)\n    if stop_position is None:\n      last_doc_id = self._get_head_document_id(DESCENDING)\n      # increment last doc id binary value by 1 to make sure the last document\n      # is not excluded\n      if isinstance(last_doc_id, ObjectId):\n        stop_position = _ObjectIdHelper.increment_id(last_doc_id, 1)\n      elif isinstance(last_doc_id, int):\n        stop_position = last_doc_id + 1\n      elif isinstance(last_doc_id, str):\n        stop_position = last_doc_id + '\\x00'\n\n    return start_position, stop_position\n","sourceCodeStart":546,"sourceCodeEnd":582,"githubUrl":"https://github.com/apache/beam/blob/12126d8942aaf848030c478b4c6a28c6af861c66/sdks/python/apache_beam/io/mongodbio.py#L546-L582","documentation":"_ObjectIdRangeTracker._get_head_document_id queries the collection sorted by _id and reads cursor[0][\"_id\"]; when the collection is empty the cursor has no first element, IndexError fires, and the code re-raises ValueError('Empty Mongodb collection'). It is used to fill in None start/stop positions for _id-range based reads.","triggerScenarios":"Running ReadFromMongoDB with the _id-based position mode against a collection that contains zero documents (or a filter that matches nothing), causing _replace_none_positions to look up the first/last document id.","commonSituations":"Pointing a pipeline at a fresh/empty collection or a wrong db/coll name; a filter argument that excludes all documents; staging environments with unseeded data.","solutions":["Verify the collection has documents: run db.<coll>.count_documents({}) in mongo before launching the job.","Check the db/coll names and the filter — a typo or over-restrictive filter can make the collection effectively empty.","Seed the collection or skip the pipeline when it is empty.","Catch ValueError around the read transform setup and short-circuit empty collections."],"exampleFix":"// before\np | ReadFromMongoDB(uri=uri, db='analytics', coll='events')\n// after\nif mongo_client['analytics']['events'].count_documents({}) == 0:\n    return  # nothing to read\np | ReadFromMongoDB(uri=uri, db='analytics', coll='events')","handlingStrategy":"validation","validationCode":"if client[db][coll].count_documents({}, limit=1) == 0:\n    raise EmptyCollectionError(f'{db}.{coll} is empty')","typeGuard":null,"tryCatchPattern":"try:\n    _ = pipeline | ReadFromMongoDB(uri=uri, db=db, coll=coll)\nexcept ValueError as e:\n    if 'Empty Mongodb collection' in str(e):\n        return  # nothing to process","preventionTips":["Check count_documents({}) > 0 before running the pipeline.","Verify db/coll names and filter against typos.","Seed or skip empty collections in staging environments."],"tags":["mongodb","empty-collection","validation"],"backgroundTag":"empty-result-set","analyzedSha":"12126d8942aaf848030c478b4c6a28c6af861c66","analyzedAt":"2026-09-13T01:50:10.254Z","contentChangedAt":"2026-09-13T01:50:10.254Z","schemaVersion":2},"datasetVersion":"2026-09-20T03:17:13.778Z"}