Home > Software design >  Mongodb change the type of all fields from string to int
Mongodb change the type of all fields from string to int

Time:09-15

I have imported a huge database from csv to mongodb. It sadly imported every value as strings. I have more then 1000 fields and 1M documents. how can i change the type from ALL fieldvalues in ALL documents from string to int without doing it for every field manually?

Thanks for help.

CodePudding user response:

I think you cannot change the datatype of all the fields in one go. You will have to do it field by field.

CodePudding user response:

Well, if you don't have nested documents, then this will work for you:

db.collection.aggregate([
  {
    "$addFields": {
      "array": {
        "$map": {
          "input": {
            "$objectToArray": "$$ROOT"
          },
          "as": "item",
          "in": {
            k: "$$item.k",
            v: {
              "$convert": {
                "input": "$$item.v",
                "to": "int",
                "onError": "$$item.v",
                "onNull": "$$item.c"
              }
            }
          }
        }
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$arrayToObject": "$array"
      }
    }
  },
  {
    "$merge": {
      "into": "collection",
      "on": "_id",
      "whenMatched": "replace",
    }
  }
])

In this, we first convert the document into an array, using $objectToArray. Then, we loop over the array and convert the values to int. Finally, we construct a new document from the array using $arrayToObject, and then we merge these new documents into the collection using $merge.

Here's the playground link.

  • Related