How to handle special characters in MongoDB collection names

Have you ever wondered what constitutes a valid MongoDB collection name? According to this source, it’s:

“any (UTF8) character(s) … which aren’t special (contains “.”, or starts with “$”)”

The alert reader may now be struck by the following quandary:

The MongoDB shell query language is JavaScript-based and collections are accessed as a property of the ‘db’ object, e.g. ‘db.my_collection.find(…)’. Yet, there will be plenty of characters that will be valid collection name characters but not valid JavaScript property name characters. What to do in such a situation? How can I run .find(…) on a collection has uses special characters in its name in the MongoDB shell?

Sure enough, “special?ch-ar!ac ter,s#a@b%c^d*” is a valid MongoDB collection name, yet attempting to use this name in the shell inevitably doesn’t end well:

> db.special?ch-ar!ac ter,s#a@b%c^d*.find()
2014-11-28T10:53:48.231+0000 SyntaxError: Unexpected token !

The way to handle special characters in a MongoDB collection name like this is to use what’s called the “square bracket notation”. (Note that is a general JavaScript technique, and not just limited to the MongoDB shell.)

Rather than access the collection directly as an object property, we can look up the property using it’s name:

> db[‘special?ch-ar!ac ter,s#a@b%c^d*’].find()

This way, we get the same result, just via an alternative syntax.

Sadly though, the MongoDB shell does not support the square bracket notion in its auto-completion.

Happily however, this is one of the many very handy little features that are packed into the MongoDB extended shell included in the 3T MongoChef multi-platform data browser and in-place editor GUI for MongoDB!

If we select a collection name in the auto-completion that contains special characters:

MongoDB Shell with Auto-Completion for Collections with Special Characters

the command will be automatically converted to square bracket notation:
MongoDB Shell and Square Bracket Notation

Furthermore, we can use the square bracket notation expression in further auto-completions:
MongoDB Shell with Auto-Completion

It’s many little nice touches like this that make using 3T MongoChef a treat! Check it out at