Monday, February 11, 2013

Distinct dumb-mongodb-name

You are forbidden to use some characters in a mongodb database name, e.g., ?, !, #, @, %, ^, *, .,   or starts with a $.  Any other UTF8 characters are valid.

There are other characters that you can use but can cause difficulties, e.g., the dash "-" character.

If you want to find the distinct values of a certain field, e.g., "location_type", in a database that has a dash in its name, you can get what you want using a mongo query like this:

> db.getSiblingDB("dumb-mongodbname").runCommand ({ distinct: 'location_type', key: 'destinationType' })
{
"values" : [
"REGION",
"CITY",
"COUNTRY"
],
"stats" : {
"n" : 999,
"nscanned" : 999,
"nscannedObjects" : 999,
"timems" : 3,
"cursor" : "BasicCursor"
},
"ok" : 1
}


If you try to reference the dumb-mongodb-name, with the dashes in the name, you'll get an error like this:


> db.dumb-mongodbname.location.find().skip(0).limit(30)
Mon Feb 11 10:13:51 ReferenceError: mongodbname is not defined (shell):1


References


http://docs.mongodb.org/manual/reference/command/distinct/
https://jira.mongodb.org/browse/SERVER-3229
http://stackoverflow.com/questions/7975185/mongodb-query-over-a-hash-with-special-chars-in-keys/7976235#7976235

Sponsor Ads


1 comment:

  1. Super option, I did not even know it. Thanks, I will know for the future.

    ReplyDelete