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



给定如下文档,如何从嵌套文档ingredients中删除或更新?任何帮助,我是这个重新思考数据库的新手。该表存储此文档,称为配方。

[
    {
        "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: [..]部分进行建模。

更新,您可以使用 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"])});  

最新更新