1

I have the following documents

{ _id:"myId", balance:1 }

and I want to change the field in number type to an array with the same number.

{ _id:"myId", balance: [1], }

tried

Collection.updateMany({ balance: { $type: 'number' } }, { $set: { balance: ["$balance"] } });

, didn't work ($balance string). How can i do this?

NeNaD
  • 18,172
  • 8
  • 47
  • 89
Andrew
  • 35
  • 5
  • @NeNaD solution below seems best for latest versions 4.2+ , here there is some ideas on how to do in different other mongo versions: https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field – R2D2 Oct 24 '22 at 08:01

1 Answers1

1

You have to wrap the update config with [] since you are using aggregation framework to update:

db.collection.update({
  balance: {
    $type: "number"
  }
},
[
  {
    $set: {
      balance: [
        "$balance"
      ]
    }
  }
])

Working example

NeNaD
  • 18,172
  • 8
  • 47
  • 89