Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB dot (.) in key name

It seems mongo does not allow insertion of keys with a dot (.) or dollar sign ($) however when I imported a JSON file that contained a dot in it using the mongoimport tool it worked fine. The driver is complaining about trying to insert that element.

This is what the document looks like in the database:

{     "_id": {         "$oid": "..."     },     "make": "saab",     "models": {         "9.7x": [             2007,             2008,             2009,             2010         ]     } } 

Am I doing this all wrong and should not be using hash maps like that with external data (i.e. the models) or can I escape the dot somehow? Maybe I am thinking too much Javascript-like.

like image 777
Michael Yagudaev Avatar asked Sep 12 '12 22:09

Michael Yagudaev


People also ask

What is the use of the dot notation in MongoDB?

Dot Notation. MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document.

Why dollar is used in MongoDB?

According to the docs, a "$" is reserved for operators. If you look at the group operator however, values need to have a dollar prefixed. These values are not operators.

What is _ID in MongoDB?

What Is MongoDB ObjectID? As MongoDB documentation explains, "ObjectIds are small, likely unique, fast to generate, and ordered." The _id field is a 12-byte Field of BSON type made up of several 2-4 byte chains and is the unique identifier/naming convention MongoDB uses across all its content.


1 Answers

MongoDB doesn't support keys with a dot in them so you're going to have to preprocess your JSON file to remove/replace them before importing it or you'll be setting yourself up for all sorts of problems.

There isn't a standard workaround to this issue, the best approach is too dependent upon the specifics of the situation. But I'd avoid any key encoder/decoder approach if possible as you'll continue to pay the inconvenience of that in perpetuity, where a JSON restructure would presumably be a one-time cost.

like image 134
JohnnyHK Avatar answered Oct 23 '22 13:10

JohnnyHK