73
MongoDBERRORNotableSystemHIGH confidence

The provided namespace (database or collection name) is invalid

What this means

This error occurs when you try to create a collection or database with a name that contains invalid characters or does not follow MongoDB's naming rules. A namespace is the concatenation of the database name and collection name.

Why it happens
  1. 1Using the ` MongoDB 73 — The provided namespace (database or collection name) is invalid | errcodes.dev errcodes-dev character in a collection name
  2. 2Attempting to create a collection with an empty string (`''`) as its name
  3. 3Using the null character (``) in a collection or database name
  4. 4Creating a collection name that is too long
How to reproduce

An `insertOne` operation implicitly tries to create a collection with a ` MongoDB 73 — The provided namespace (database or collection name) is invalid | errcodes.dev errcodes-dev in its name.

trigger — this will error
trigger — this will error
// Collection names cannot contain '
#x27;. db.getCollection("invalid$name").insertOne({ doc: 1 });

expected output

MongoServerError: Invalid collection name: invalid$name

Fix 1

Sanitize and Correct the Namespace

WHEN Creating collections or databases dynamically.

Sanitize and Correct the Namespace
// Remove invalid characters before creating the collection.
const dirtyName = "my$collection";
const cleanName = dirtyName.replace(/$/g, ""); // "mycollection"
db.getCollection(cleanName).insertOne({ doc: 1 });

Why this works

Ensure that any user-provided or dynamically generated names are sanitized to remove invalid characters before being used as collection or database names.

Fix 2

Adhere to Naming Restrictions

WHEN Manually naming collections and databases.

Why this works

Review MongoDB's naming restrictions in the documentation. Avoid special characters and ensure names are of a reasonable length and do not start with reserved prefixes.

What not to do

Use characters that have special meaning in other systems (like '/') thinking they will work

Different filesystems and systems have different reserved characters. Sticking to simple alphanumeric names with underscores or dashes is the safest approach for maximum compatibility.

Sources
Official documentation ↗

mongodb/mongo src/mongo/base/error_codes.yml

Naming Restrictions

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All MongoDB errors