mongodb import object with numbers as keys results in array
Asked Answered
S

1

6

I have a simple .json which I am trying to import:

{
  "data": {
    "plans": {
      "1": "14",
      "2": "20",
      "3": "40"
    }
  }
}

When I use MongoDB Compass to directly import the json file, the plans object is converted into an array:

{ "_id": { "$oid": "5fe3ff5d909016064978f2bd" }, "plans": [null, "14", "20", "40"] }

Am I doing something wrong? Or can I not use numbers as keys in JSON

Scotland answered 24/12, 2020 at 2:41 Comment(1)
This is working using mongoimport command, might be there is some issue in mongo compass, why don't you ask this in mongodb community forums.Exoskeleton
V
4

MongoDB uses BSON, the following note is from that spec:

Array - The document for an array is a normal BSON document with integer values for the keys, starting with 0 and continuing sequentially. For example, the array ['red', 'blue'] would be encoded as the document {'0': 'red', '1': 'blue'}. The keys must be in ascending numerical order.

The object format you are using matches that description, so some drivers will confuse it for an array.

It might be that the data is being stored properly, but when you query it, the client is converting to an array.

Try retrieving the document with something else, perhaps the mongo shell.

Vlad answered 25/12, 2020 at 11:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.