Tim
Tim

Reputation: 99428

Why is a collection whose name starts with an underscore treated differently?

The name of a collection must start with either a letter or an underscore.

Then why does the first one works, while the last two don't? Thanks.

> db.getCollection("_20160712").find()
{ "_id" : ObjectId("57a38e4991c3b3a393e9be2b"), "dimension_id" : 2, "attribute" : "good", "hour" : "20160712_06", "frequency_count" : 100 }
> db._20160712.find()
2016-08-04T14:53:56.963-0400 E QUERY    [thread1] TypeError: db._20160712 is undefined :
@(shell):1:1
> db['_20160712'].stats()
2016-08-04T14:52:43.964-0400 E QUERY    [thread1] TypeError: db._20160712 is undefined :
@(shell):1:1

Upvotes: 8

Views: 4394

Answers (1)

Mr Tarsa
Mr Tarsa

Reputation: 6652

According to documentation

If your collection name includes special characters, such as the underscore character, then to access the collection use the db.getCollection() method in the mongo shell or a similar method for your driver.

According to documentation db.getCollection(name) method

Returns a collection object that is functionally equivalent to using the db.collectionName syntax. The method is useful for a collection whose name might interact with the shell itself, such as names that begin with _ or that match a database shell method.

So, actually you can access collection with name that includes underscore (not on the first position) without db.getCollection() method.

Next examples are valid in mongo Shell

db.collection_.find();
db.collection_1.find();

Only when underscore is on the first position, the only way you can access collection in mongo Shell is by using db.getCollection() method.

It's not treated differently, it's just how mongo Shell works.

Upvotes: 13

Related Questions