Hi @promisetech,
JSON requires key names to be strings, so using numeric strings is technically valid. However, JavaScript has some interesting assumptions (and unexpected coercion) for numeric values so I’d recommend against using numeric strings as keys.
Here’s an example of JavaScript producing unexpected results for what appear to be similar objects.
a) Doc with string key names that could be interpreted as numbers:
doc = {
"data": {
"plans": {
"2": "20",
"1": "14",
"3": "40"
}
}
}
Output in a `mongo` or `node` shell (numeric strings)
{
"data": {
"plans": {
"1": "14",
"2": "20",
"3": "40"
}
}
}
==> JavaScript sorts the object keys
b) Doc with string key names that are alphanumeric:
doc = {
"data": {
"plans": {
"v2": "20",
"v1": "14",
"v3": "40"
}
}
}
Output in a `mongo` or `node` shell (alphanumeric strings)
{
"data": {
"plans": {
"v2": "20",
"v1": "14",
"v3": "40"
}
}
}
==> Object keys are maintained in insertion order!
As my example above demonstrates, the order of keys in a generic JavaScript Object is not defined (or guaranteed to be preserved). In particular, there is some legacy handling for key names that can be parsed as a 32-bit integer: 164 - v8 - V8 JavaScript Engine - Monorail. JavaScript does have order-preserving types like Map
objects and arrays, but the default Object behaviour is almost what you expect (except when it isn’t).
Since Compass is a JavaScript application, it inherits some of these legacy quirks that have to be coded around.
The mongoimport
tool is written in Go, so its JSON implementation does not have to deal with the added quirks of JavaScript handling.
Regards,
Stennie