Error
Error Code: 48

MongoDB Error 48: Collection or Index Exists

📦 MongoDB
📋

Description

MongoDB Error 48, 'Namespace Exists', occurs when an operation attempts to create a collection, index, or view with a name that is already in use within the current database. This typically happens during database schema initialization or when re-running creation scripts.
💬

Error Message

Namespace Exists
🔍

Known Causes

3 known causes
⚠️
Collection Name Conflict
You tried to create a new collection using `db.createCollection()` or implicitly via an insert operation, but a collection with the same name already exists in the database.
⚠️
Duplicate Index Creation
An attempt was made to create an index on a collection using `db.collection.createIndex()`, but an index with the exact same specification already exists for that collection.
⚠️
View Name Collision
An operation to create a new view using `db.createView()` failed because a view or collection with the specified name already occupies that namespace.
🛠️

Solutions

4 solutions available

1. Drop and Recreate Collection easy

Remove existing collection first

1
Drop existing collection
db.existingCollection.drop()
2
Create new collection
db.createCollection("existingCollection", {
  validator: { $jsonSchema: { ... } }
})

2. Use Different Name easy

Choose unique collection name

1
Check existing collections
show collections
2
Use unique name
db.createCollection("users_v2")

3. Rename Existing Collection easy

Move existing collection out of the way

1
Rename existing collection
db.existingCollection.renameCollection("existingCollection_backup")
2
Create new collection with original name
db.createCollection("existingCollection")

4. Check for View with Same Name easy

Views and collections share namespace

1
List views
db.getCollectionInfos({ type: "view" })
2
Drop view if exists
db.existingView.drop()
🔗

Related Errors

5 related errors