Ecto: Best way to update a map field, perserving existing values?

What is the best way to update or add a key to a map field - preserving existing key/values?

schema "authors" do
  field :additional_data, :map

Reading through the docs and googling around, it seems my options are:

  • Manually merge existing map with incoming map in my changeset.
  • Convert my map field to an embedded schema and update it that way.

Are there other options I’m missing?


1 Like

If you use Postgres, then you can merge two jsonb objects on a database level using || operator:

select '{"a": 1, "b":2}'::jsonb || '{"b": 3, "c":4}'::jsonb


{"a": 1, "b": 3, "c": 4}
1 Like

In the end you’ll be merging the map somewhere. Ecto doesn’t have a concept of merging at the field value level.

1 Like