aknuds1
aknuds1

Reputation: 67997

RethinkDB - how to filter arrays in nested objects when updating?

With RethinkDB, how do I update arrays in nested objects so that certain values are filtered out?

Consider the following program, I would like to know how to write an update query that filters out the value 2 from arrays contained in votes sub objects in documents from the 'dinners' table:

import rethinkdb as r
from pprint import pprint


with r.connect(db='mydb') as conn:
    pprint(r.table('dinners').get('xxx').run(conn))
    r.table('dinners').insert({
        'id': 'xxx',
        'votes': {
            '1': [1, 2, ],
        },
    }, conflict='replace').run(conn)

# How can I update the 'xxx' document so that the value 2 is
# filtered out from all arrays contained in the 'votes' sub object?

Upvotes: 1

Views: 309

Answers (1)

RonZ
RonZ

Reputation: 467

You can use the usual filter method together with object coersion:

def update_dinner(dinner):
    return {
        'votes': dinner['votes']
        .keys()
        .map(lambda key: [
            key,
            dinner['votes'][key].filter(lambda vote_val: vote_val.ne(2)),
       ])
        .coerce_to('object')
    }

r.table('dinners').update(update_dinner).run(conn)

Upvotes: 3

Related Questions