skip to Main Content

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.

2

Answers


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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search