如何从嵌套文档数组中删除/更新

时间:2019-06-15 18:34:47

标签: json rethinkdb rethinkdb-python

给出以下文档,如何从嵌套文档ingredients中删除或更新?任何帮助,我都是这个rethinkdb的新手。该表存储了称为配方的文档。

[
    {
        "cook": "9 min",
        "id": "be63fc32-c1b5-4c67-a967-b6868f095216",
        "inactive": "20 min",
        "ingredients": [
            "2 cups fresh parsley leaves, chopped",
            "8 large sprigs fresh thyme, chopped",
            "4 large sprigs fresh rosemary, chopped",
            "3 cloves garlic, minced",
            "1 small shallot, diced",
            "2 tablespoons cracked black peppercorns",
            "2 tablespoons cracked pink peppercorns",
            "1 1/4 cups extra-virgin olive oil",
            "8 skin-on chicken thighs",
            "Flaky salt, such as Maldon, for seasoning",
            "Salad, for serving"
        ],
        "level": "Easy",
        "prep": "5 min",
        "title": "Asian Grilled Salmon",
        "total": "34 min",
        "yields": "6 servings"
    },
    ....

正如您在下面看到的,我尝试了一下,并且有效。但是我想知道是否有更好的方法。

class Ingredients:
    def __init__(self, name):
        self.name = name

    @classmethod
    def update(self, recipe, name, position):
        __db__ = recipe.__class__.__db__()
        __table__ = recipe.__class__.__table__()
        result = (
            __table__.get(recipe.id)
            .update(
                {
                    "ingredients": __db__.r.row["ingredients"].change_at(
                        position, name
                    )
                }
            )
            .run(__db__.conn)
        )

        return recipe.ingredients

    @classmethod
    def destroy(self, recipe, recipe_name):
        __db__ = recipe.__class__.__db__()
        __table__ = recipe.__class__.__table__()
        __table__.get(recipe.id).update(
            {
                "ingredients": __db__.r.row["ingredients"].filter(
                    lambda name: name != recipe_name
                )
            }
        ).run(__db__.conn)

        return recipe.ingredients

Ingredients类是尝试在Python中为父文档的ingredients: [..]部分建模。

1 个答案:

答案 0 :(得分:2)

要进行更新,您可以使用map遍历配料,找到要更新并更改其值的配料:

r.db("test").table("sample").get("be63fc32-c1b5-4c67-a967-b6868f095216")
   .update({
     ingredients: r.row("ingredients").map(function(sub){  
       return r.branch(sub.eq("2 cups fresh parsley leaves, chopped"),
         "2 cups fresh baby poo, marinated", sub)
     })
   })  

删除,您可以使用difference函数:

r.db('test').table('sample').get('be63fc32-c1b5-4c67-a967-b6868f095216')
  .update({ingredients: r.row('ingredients')
    .difference(["4 large sprigs fresh rosemary, chopped"])});