Question: Find and update a collection in JSONB

Question

Find and update a collection in JSONB

Answers 0
Added at 2017-01-01 10:01
Tags
Question

I have a Rails 5.0 app with a JSONB column called data, which contains an array of hashes:

[
    {'event': 'web_session', 'user_id': 1, 'count': 13},
    {'event': 'web_session', 'user_id': 2, 'count': 10},
    {'event': 'web_session', 'user_id': 3, 'count': 42}
]

How would I update one of the hashes, e.g. matching 'user_id': 2, with a different count value?

Is this the most efficient way (I'd potentially have ~1 million hashes):

h = data.find {|h| h['user_id'] == 2}
h['count'] = 43
save
Answers
Source Show
◀ Wstecz