kjellhaaland
kjellhaaland

Reputation: 166

How to convert all elements in an array from strings to numbers in MongoDB

Given a collection of MongoDB documents where each document have an array of numbers stored as strings. How do i modify all documents to store the element as numbers instead of strings?

Currently, the documents are structured like this:

{
"coordinates": ["7.83", "58.08"]
}

The desired output would be like this

{
"coordinates": [7.83, 58.08]
}

The collection have 1M+ documents, and solutions that involves processing the documents in code, would not be desirable.

I have tried to use the $toDouble operator combined with $updateMany, without success.

Upvotes: 1

Views: 746

Answers (1)

Gibbs
Gibbs

Reputation: 22956

db.collection.update({},
[ //Aggregate update
  {
    "$set": {
      "coordinates": {
        $map: {
          input: "$coordinates",
          in: {
            $toDouble: "$$this" //Aggregate operators required to convert
          }
        }
      }
    }
  }
],
{
  "multi": true,
  "upsert": false
})

PLayground

Upvotes: 2

Related Questions