Mauro
Mauro

Reputation: 127

How to convert string to array of int MongoDB

in my project I have an excel file that is converted in a mongodb structure data.

This is an example row:

appartamento:{
    nome: 'Appartamento',
    via: 'Via Roma 120',
    ids_stile: '2, 3 11',
    ids_personaggi: '8, 9, 21'
}

Where 'ids_stile' and 'ids_personaggi' are strings.

Is it possible to convert the ids_stile and ids_personaggi in a collection of integers to have a structure like this?

appartamento:{
    nome: 'Appartamento',
    via: 'Via Roma 120',
    ids_stile: [2, 3,  11],
    ids_personaggi: [8, 9, 21]
}

Thanks

Upvotes: 2

Views: 996

Answers (2)

J.F.
J.F.

Reputation: 15235

If you want to use mongo to do this, try this query:

db.collection.aggregate([
  {
    "$match": {
      "id": 0
    }
  },
  {
    "$set": {
      "appartamento.ids_stile": {
        "$split": [
          "$appartamento.ids_stile",
          ","
        ]
      },
      "appartamento.ids_personaggi": {
        "$split": [
          "$appartamento.ids_personaggi",
          ","
        ]
      }
    }
  },
  {
    "$project": {
      "appartamento.ids_stile": {
        "$map": {
          "input": "$appartamento.ids_stile",
          "as": "newArray",
          "in": {
            "$convert": {
              "input": "$$newArray",
              "to": "int",
              
            }
          }
        }
      },
      "appartamento.ids_personaggi": {
        "$map": {
          "input": "$appartamento.ids_personaggi",
          "as": "newArray",
          "in": {
            "$convert": {
              "input": "$$newArray",
              "to": "int",
              
            }
          }
        }
      },
      "appartamento.nome": 1,
      "appartamento.via": 1
    }
  }
])

Basically is get the document you want (I've used appartamento.nome but you can match by _id or whatever you want).
Then, modify the fields using $set and $split to create an string array dividied by ','.
After that project the fields overwriting these two with a new array using $map where each value from string array now is converted to int.

Example here

Edit:

To do that with many documents, only is necessary remove the $match stage.

Example here

Upvotes: 3

Robert
Robert

Reputation: 2763

use string split and then use map and parse each string value to number.

const appartamento = {
    nome: 'Appartamento',
    via: 'Via Roma 120',
    ids_stile: '2, 3, 11',
    ids_personaggi: '8, 9, 21'
};

const appartamento2 = {
    nome: 'Appartamento',
    via: 'Via Roma 120',
    ids_stile: appartamento.ids_stile.split(", ").map(s => +s),
    ids_personaggi: appartamento.ids_personaggi.split(", ").map(s => parseInt(s)),
}

console.log(appartamento2)

Upvotes: 2

Related Questions