ionush
ionush

Reputation: 353

mongodb import object with numbers as keys results in array

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

Upvotes: 6

Views: 572

Answers (1)

Joe
Joe

Reputation: 28326

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.

Upvotes: 4

Related Questions