RethinkDB - 如何在更新时过滤嵌套对象中的数组?

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

使用 RethinkDB,我如何更新嵌套对象中的数组以便过滤掉某些值?

考虑以下程序,我想知道如何编写一个更新查询,从 'dinners' [=17] 文档中的 votes 子对象中包含的数组中过滤出值 2 =]:

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?

您可以将常用的过滤方法与对象强制一起使用:

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)