MongoDB, replace state names with abbreviations

Viewed 144

I want to update a collection so that an address uses state abbreviations, "AK", rather then the long names, "Alaska".

How can I do an updateMany with logic to handle this?

pseudo code

const states = [
  {name:"Alaska", abbreviation:"AK"},
  {name:"Alabama", abbreviation:"AL"},
...
Users.updateMany({"address.state": {$nin: states.abbreviation},
{$set: {"address.state": { states.find(state => state.name == address.state).abbreviation } } }
}
1 Answers

You can use bulk writes with 50 updateMany commands. You do need one command per state but you can send them to the server in a single operation.

Related