Search code examples
mongodbmongodb-shell

Unable to access MongoDB collection from shell when the name contains '-'


I have a collection named GoldenGlobes-emotion in my MongoDB 2.6.9 I found I can not access this collection from the MongoDB shell When ever I try to access the collection, for example

db.GoldenGlobes-emotion.findOne()

I always got this:

ReferenceError: emotion is not defined

But it works well when I access the collection form Python with PyMongo. Is this a shell bug? Or '-' is a reserved character?


Solution

  • Try db["GoldenGlobes-emotion"].findOne().

    The MongoDB shell is a Javascript interpreter. Javascript does not allow hyphens in variable names, because it interprets them as the minus-operator. However, you can also access object-fields with string literals by using the array-syntax. In that case, this restriction does not apply.