Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can I drop a collection in MongoDB with two dashes in the name?
To drop a collection in MongoDB that has special characters like two dashes in its name, you need to use the getCollection() method instead of direct dot notation, since MongoDB cannot parse collection names with special characters using standard syntax.
Syntax
db.getCollection("collectionNameWithSpecialCharacters").drop();
Create Sample Collection
First, let's create a collection with two dashes in the name ?
db.createCollection("company--EmployeeInformation");
{ "ok" : 1 }
Insert Sample Data
Add some documents to the collection ?
db.getCollection("company--EmployeeInformation").insertMany([
{"CompanyName": "Amazon", "EmployeeName": "Chris"},
{"CompanyName": "Google", "EmployeeName": "Robert"}
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5cd7c5ff6d78f205348bc654"),
ObjectId("5cd7c60b6d78f205348bc655")
]
}
Verify Collection Contents
Display all documents from the collection ?
db.getCollection("company--EmployeeInformation").find();
{ "_id" : ObjectId("5cd7c5ff6d78f205348bc654"), "CompanyName" : "Amazon", "EmployeeName" : "Chris" }
{ "_id" : ObjectId("5cd7c60b6d78f205348bc655"), "CompanyName" : "Google", "EmployeeName" : "Robert" }
Drop the Collection
Now drop the collection with two dashes in the name ?
db.getCollection("company--EmployeeInformation").drop();
true
Key Points
- Use
getCollection()for collection names with special characters like dashes, spaces, or numbers. - The
drop()method returnstrueif the collection was successfully dropped. - Direct dot notation like
db.company--EmployeeInformation.drop()will not work due to parsing issues.
Conclusion
When dropping MongoDB collections with special characters in their names, always use db.getCollection("collection-name").drop(). This method handles special characters that would otherwise cause syntax errors with standard dot notation.
Advertisements
