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



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

考虑以下程序,我想知道如何编写一个更新查询,从"晚餐"表中文档中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)

最新更新