Error
Error Code:
118
MongoDB Error 118: Namespace Not Sharded
Description
Error 118, 'Namespace Not Sharded', indicates that an operation requiring a sharded collection or database was attempted on a target that is not sharded. This typically occurs when executing sharding-specific commands against a collection or database that has not been configured for sharding.
Error Message
Namespace Not Sharded
Known Causes
4 known causesCollection Not Sharded
The most common cause is attempting to execute a sharding-specific command or operation on a collection that has not yet been enabled for sharding.
Database Sharding Not Enabled
The target database for the operation might not have sharding enabled, meaning its collections cannot be sharded without prior configuration.
Incorrect Namespace Target
The specified namespace (database.collection) in the sharding command might be incorrect or refer to a different, non-sharded collection.
Incomplete Sharding Setup
The MongoDB cluster might not be fully configured for sharding, leading to collections appearing non-sharded even if the intent was to shard them.
Solutions
3 solutions available1. Enable Sharding for the Namespace medium
This is the most direct solution if sharding is intended.
1
Connect to your MongoDB shell.
mongosh
2
Enable sharding for the database containing the namespace.
sh.enableSharding("<database_name>")
3
Shard the specific collection (namespace). You will need to choose a shard key.
sh.shardCollection("<database_name>.<collection_name>", { <shard_key_field>: 1 })
4
Verify that the namespace is now sharded.
db.getCollectionInfos({ name: "<collection_name>" })
2. Disable Sharding for the Namespace medium
If sharding was enabled accidentally or is no longer needed.
1
Connect to your MongoDB shell.
mongosh
2
Disable sharding for the specific collection. This is only possible if the collection is empty.
sh.disableSharding("<database_name>.<collection_name>")
3
If the collection is not empty, you will need to drop the collection or move its data to another collection before disabling sharding.
db.getSiblingDB("<database_name>").dropDatabase("<collection_name>")
4
After the collection is empty, you can disable sharding.
sh.disableSharding("<database_name>.<collection_name>")
3. Recreate the Namespace without Sharding easy
A straightforward approach if the data can be easily reinserted.
1
Connect to your MongoDB shell.
mongosh
2
Drop the existing sharded collection.
db.getSiblingDB("<database_name>").getCollection("<collection_name>").drop()
3
Create the collection again. By default, new collections are not sharded.
db.createCollection("<collection_name>")
4
Reinsert your data into the newly created collection.
db.getSiblingDB("<database_name>").getCollection("<collection_name>").insertMany([...])