Update the document, setting the type to double for field that currently have the type string.

Problem Statement

Write mongodb query to update the document, setting the type to double for field 'age' that currently have the type string.

Collection Name: students

[
  {
    _id: ObjectId('6626fb9e6548c947e716c9b7'),
    name: 'Joe Rogan',
    age: 35,
    country: 'USA'
  },
  {
    _id: ObjectId('6626fe516548c947e716c9b9'),
    name: 'Chris Williamson',
    age: 35.4,
    country: 'Austrelia'
  },
  {
    _id: ObjectId('6626fe666548c947e716c9ba'),
    name: 'Lex',
    age: '28',
    country: 'USA'
  }
] 

For more explaination of $type operator see : What is $type operator and how to use it?

Solution

 db.dataTypes.updateMany({"age":{$type:["string"]}},[{$set:{"age":{$toDouble:'$age'}}}])
Explaination:

$toDouble will parse string value into double and set it again to age field. '$age' is used to take value of age from document to parse.