Delete a collection from MongoDB with special characters?

To delete a MongoDB collection that contains special characters in its name (like underscore _ or hyphen -), use the getCollection() method followed by drop().

Syntax

db.getCollection("collectionNameWithSpecialChars").drop();

Create Sample Data

Let us create a collection with special characters and add some documents ?

db.createCollection("_personalInformation");
{ "ok" : 1 }
db.getCollection('_personalInformation').insertMany([
    {"ClientName":"Chris","ClientCountryName":"US"},
    {"ClientName":"Mike","ClientCountryName":"UK"},
    {"ClientName":"David","ClientCountryName":"AUS"}
]);
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5c9158bb4afe5c1d2279d6b2"),
        ObjectId("5c9158c84afe5c1d2279d6b3"),
        ObjectId("5c9158d54afe5c1d2279d6b4")
    ]
}

Verify Collection Contents

Display all documents to confirm the collection exists ?

db.getCollection('_personalInformation').find().pretty();
{
    "_id" : ObjectId("5c9158bb4afe5c1d2279d6b2"),
    "ClientName" : "Chris",
    "ClientCountryName" : "US"
}
{
    "_id" : ObjectId("5c9158c84afe5c1d2279d6b3"),
    "ClientName" : "Mike",
    "ClientCountryName" : "UK"
}
{
    "_id" : ObjectId("5c9158d54afe5c1d2279d6b4"),
    "ClientName" : "David",
    "ClientCountryName" : "AUS"
}

Delete the Collection

Now delete the collection with special characters using getCollection() method ?

db.getCollection("_personalInformation").drop();
true

Key Points

  • Use getCollection("name") for collection names with special characters like _, -, or spaces.
  • The drop() method returns true if the collection was successfully deleted.
  • Standard dot notation db.collectionName.drop() only works for names without special characters.

Conclusion

The getCollection() method allows you to safely reference and delete MongoDB collections with special characters in their names. This method ensures proper handling of collection names that cannot use standard dot notation.

Updated on: 2026-03-15T00:19:10+05:30

542 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements