35

I have found a collection in one of our MongoDB databases with the name my.collection.

Is there a way to access this collection from the MongoDB shell, despite it having a point in the name?

> db.my.collection.findOne();
null

I'm pretty sure that that is not correct.

Rich
  • 15,602
  • 15
  • 79
  • 126
  • It works for map/reduce collection which have a dot in their name, e.g. `tmp.mr.mapreduce_1294927200_2363` – Nekresh Jan 13 '11 at 14:07

4 Answers4

103

try this instead:

db["my.collection"].findOne();

you run into the same issue with hyphens or any other name that does not match on [a-zA-Z_$][0-9a-zA-Z_$]

This limitation comes from valid named for javascript object properties.

EdChum
  • 376,765
  • 198
  • 813
  • 562
Laura
  • 1,039
  • 1
  • 7
  • 3
  • 7
    I believe this should be the accepted answer because it explains the syntax and gives a useful workaround. – jschreiner Jan 27 '14 at 12:30
  • Could you please tell me how to drop 'Model\Tag_keys' collection. It is not working with this method `db['Model\Tag_keys'].drop()` – Irshad Khan Apr 05 '18 at 10:36
  • For db names that do not respect js object properties name rules, there is another solution below, based on `db.getCollection('_name')` – DrakaSAN Jul 10 '19 at 14:35
13

if collection name is "my.collection"

db.my.collection.findOne(); // OK
null

if collection name is "my.1.collection"

db.my.1.collection.findOne(); // Not OK
SyntaxError: missing ; before statement

Fix:

db["my.1.collection"].findOne(); // Now is OK
null

user1946163
  • 139
  • 1
  • 3
11

Another foolproof method is:

db.getCollection("_SCHEMA").find()

While in the case of a underscore in the name, still cause a error with @Laura answer:

> db["_SCHEMA"].find()
2016-07-18T17:44:16.948+0200 E QUERY    [thread1] TypeError: db._SCHEMA is undefined :
@(shell):1:1
DrakaSAN
  • 7,673
  • 7
  • 52
  • 94
1

Your code is correct. If it returns null it means that the collection is empty.

Javier Ferrero
  • 8,741
  • 8
  • 45
  • 50
  • 1
    With a similar problem I found mongo shell giving the Error "SyntaxError: unexpected token ILLEGAL" ... I found Laura's answer below is the way to access a collection with a period in the name. – Kickaha Oct 18 '15 at 02:09