0

In my movies collection, I have a year field, which is a String (example: "year": "2010")

I want to update year in all my collection, changing it to an int so I can compare it to other int fields.

I tried the following:

db.movies.updateMany({}, {$set: {year: new NumberInt("$year")}})

which changes every year value to 0 (int), and not the string value converted to int.

I also tried db.movies.updateMany({}, {$set: {year: parseInt("$year", 10)}}), but it returns NaN everywhere.

I have been trying for a while now and I can't see what I'm doing wrong! Any help much appreciated :)

DrunkDevKek
  • 469
  • 4
  • 17

1 Answers1

0

You can try classic way

var customUpdate = function(document) {
  var val = parseInt(document.year, 10);
  db.movies.update(
    {_id:document._id}, 
    {$set: {year: val}}
  );
}

db.movies.find().forEach(customUpdate)

Update MongoDB field using value of another field

Community
  • 1
  • 1
Le Nhat Anh
  • 153
  • 1
  • 8