apache/beam · error · ValueError

WriteToMongoDB db param must be specified as a string

Error message

WriteToMongoDB db param must be specified as a string

What it means

WriteToMongoDB.__init__ validates that the db parameter is a Python str and raises ValueError otherwise. The database name is stored and later used to build the MongoDB client, so non-string values would form invalid write targets.

Solutions

  1. Pass the db name as a str, e.g. db='mydb'.
  2. Coerce config/env values: check for None, then str(value) or bytes.decode('utf-8').
  3. Add an upstream assertion that the db name is a non-empty string before constructing the transform.
  4. Fix argument order so the intended value reaches db.

Example fix

// before
sink = WriteToMongoDB(uri=uri, db=config.get('db'), coll='results')
// after
db = config.get('db')
assert isinstance(db, str) and db
sink = WriteToMongoDB(uri=uri, db=db, coll='results')
Defensive patterns

Strategy: type-guard

Validate before calling

if not isinstance(db, str) or not db:
    raise ValueError('db must be a non-empty string')

Type guard

def is_db_name(v) -> bool:
    return isinstance(v, str) and bool(v)

Try / catch

try:
    sink = WriteToMongoDB(uri=uri, db=db, coll=coll)
except ValueError as e:
    raise ConfigError(f'bad Mongo sink config: {e}') from e

Prevention

When it happens

Trigger: Calling WriteToMongoDB(uri=..., db=<non-string>, coll=...) — db=None from an unset config, bytes from a config file, or a positional-argument mix-up.

Common situations: Unset environment variables for the sink database; YAML/JSON config returning non-str types; refactoring that swapped db/coll arguments.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


AI-assisted analysis of apache/beam@12126d8942 (2026-09-13). Data as JSON: /api/errors/785acf85a56ea12d. Report an issue: GitHub.

Appendix: source

Thrown at sdks/python/apache_beam/io/mongodbio.py:707

    Args:
      uri (str): The MongoDB connection string following the URI format
      db (str): The MongoDB database name
      coll (str): The MongoDB collection name
      batch_size(int): Number of documents per bulk_write to  MongoDB,
        default to 100
      extra_client_params(dict): Optional `MongoClient
       <https://api.mongodb.com/python/current/api/pymongo/mongo_client.html>`_
       parameters as keyword arguments

    Returns:
      :class:`~apache_beam.transforms.ptransform.PTransform`

    """
    if extra_client_params is None:
      extra_client_params = {}
    if not isinstance(db, str):
      raise ValueError("WriteToMongoDB db param must be specified as a string")
    if not isinstance(coll, str):
      raise ValueError(
          "WriteToMongoDB coll param must be specified as a string")
    self._uri = uri
    self._db = db
    self._coll = coll
    self._batch_size = batch_size
    self._spec = extra_client_params

  def expand(self, pcoll):
    return (
        pcoll
        | beam.ParDo(_GenerateObjectIdFn())
        | Reshuffle()
        | beam.ParDo(
            _WriteMongoFn(
                self._uri, self._db, self._coll, self._batch_size, self._spec)))

View on GitHub (pinned to 12126d8942)