Entering a large array into the database

Hello. There is an array consisting of two string values, but they are without keys. Is it possible to somehow bring them all into the database without looping through the loop and so that the first number in the pair is the key, and the second is the value?

Hello Игорь Князьков :wave:

I think it can be done. But, there are some questions to be answered before that.

  1. The array is something like this, confirm: [ [ "12.345", "0.1234" ], [ "5.6789", "0.6789" ] ]

  2. And you want to store it, yes, as key-value pairs, but all these keys and values within one document? Something like this:
    { _id: 1, array: [ { "12.345": "0.1234" }, { "5.6789": "0.6789" } ] }

  3. Is the data in a file or as an array object?

  4. What is the MongoDB version?

  5. How are you planning to use this data?

  1. Yes;
  2. Yes. But I want to slightly correct my question. I will have one more same array and I would like to write it to this document too. Something like that:

{ _id: 1, array1: [ { “12.345”: “0.1234” }, { “5.6789”: “0.6789” } ], array2:[ { “12.5”: “0.14” }, { “5.69”: “0.89” } ]}

  1. Array object;
  2. 4.2;
  3. In general, this is data from the crypto-exchange. It is planned that they will be updated online and when I need some information I will contact the database.

How do you determine which data goes into array1 and array2 ? You have one input array.

When they come from the exchange they have different names: asks: and bids:

From the mongo shell:

array_input = [ [ "12.345", "0.1234" ], [ "5.6789", "0.6789" ] ]

db.collection.save( { _id: 1, array: array_input } )

This saved the array into a document in the collection. Now, we can convert the array elements into key-value pairs using an aggregate query.

db.collection.aggregate( [
  { 
      $unwind: "$array" 
  },
  { 
      $addFields: { array: [ "$array" ] } 
  },
  { 
      $addFields: { array: { $arrayToObject: "$array"  } } 
  },
  { 
      $group: { _id: "$_id", array: { $push: "$array" } } 
  }
] )

The output:

{
        "_id" : 1,
        "array" : [
                  {
                        "12.345" : "0.1234"
                  },
                  {
                        "5.6789" : "0.6789"
                  }
        ]
}
1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.