I have a database something like this:
{
"_id" : ObjectId("61b69c02f92253fbe1017f23"),
"nombre" : "Judd",
"primer_apellido" : "Saterthwait",
"segundo_apellido" : "Wabb",
"identificacion" : "929499610",
"genero" : "M",
"edad" : "22",
"seguridad_social" : "0",
"telefono" : "4796610146",
"banco" : "BANK OF AMERICA",
"cuenta" : "36687045607282",
"ciudad" : "Lihu",
"desarrollador" : "senior",
"trabaja_en" : "Thoughtsphere",
"correo" : "[email protected]",
"pass" : "aea6d8bed55166ecde96d8ca1c687234",
"fec_ultimo_acceso" : "2021-04-30",
"tiene_hijos" : "1",
"carnetizado" : "0",
"activo" : "0",
"reportes" : "1"
}
{
"_id" : ObjectId("61b69c02f92253fbe1017f39"),
"nombre" : "Alleyn",
"primer_apellido" : "Corneljes",
"segundo_apellido" : "Andrivel",
"identificacion" : "615842724",
"genero" : "M",
"edad" : "46",
"telefono" : "6722395057",
"banco" : "CITYBANK",
"cuenta" : "4508531326650291",
"ciudad" : "Sambonggede",
"desarrollador" : "senior",
"trabaja_en" : "Skyndu",
"correo" : "[email protected]",
"pass" : "a16ebf90ff6d116d220db8ede95ae253",
"fec_ultimo_acceso" : "2021-04-30",
"tiene_hijos" : "1",
"carnetizado" : "1",
"activo" : "0",
"reportes" : "2"
}
{
"_id" : ObjectId("61b69c02f92253fbe1017f75"),
"nombre" : "Tessa",
"primer_apellido" : "Biesinger",
"segundo_apellido" : "De Meis",
"identificacion" : "12958583",
"genero" : "F",
"edad" : "50",
"seguridad_social" : "1",
"telefono" : "7465255759",
"banco" : "GM2",
"cuenta" : "6709265650990708",
"ciudad" : "Wuyang",
"desarrollador" : "junior",
"trabaja_en" : "Babbleset",
"correo" : "[email protected]",
"pass" : "0f4e5cee2132609be62102ab945c723a",
"fec_ultimo_acceso" : "2021-04-30",
"tiene_hijos" : "1",
"carnetizado" : "0",
"activo" : "1",
"reportes" : "2"
}
What happens is that in the 'edad' key (age in english), it is as a number but in string, for example: "45". I want to change the data type from string "45" to number 45, of all the objects stored in the database. How can I do it? (I think it is with forEach)
CodePudding user response:
Query
- pipeline update requires MongoDB >= 4.2
- change the age field from string to integer, to all documents ({} matches to all), using the
$toInt
aggregate operator. - use
updateMany
method of your driver or set option{"multi" : true}
to update all the documents.
update({},[{"$set": {"edad": {"$toInt": "$edad"}}}],{"multi" : true})