MongoDB - 如果嵌套在数组内的对象与查询匹配,则查找并更新数组元素

问题描述 投票:0回答:1

我有一个使用 PyMongo 和 Beanie 的 FastAPI 应用程序。

我想过滤给定艺术家 ID 的推荐文档数组,并更新它的批准、注释和反馈键。

重要

艺术家是另一个收藏的可选链接:

artist: Optional[Link[ArtistCollection]]

     {
         "_id": "65a16b0469f8f0425e8d47a9",
         "created_at": "2024-01-12T16:38:28.403000",
         "status": "open",
         "notes": null,
         "event": null,
         "recomendations": [
             {
                 "approve": null,
                 "disapprove": null,
                 "notes": "",
                 "feedback": "",
                 "score": null,
                 "artist": {
                     "id": "182957",
                     ..., # Other Fields
                 }
             },
             ...,
         ]
      }

我尝试了以下方法,但没有结果:

    recommendation = await Recomendations.find_one(
        {"_id": ObjectId(recomendation_id)},
        fetch_links=True,
    )
    updated_document = await recommendation.update(
        {"$set": {
            "artist_recomendations.$[elem].approve": datetime.now(),
            "artist_recomendations.$[elem].notes": artist_recomendation.notes,
            "artist_recomendations.$[elem].feedback": artist_recomendation.feedback,
        }},
        array_filters=[{"elem.artist.$id": artist_id}]
    )

    return updated_document
mongodb nosql pymongo fastapi odm
1个回答
0
投票

好的,发现问题了,我必须按艺术家过滤,并使用 DBRef 对象来进行正确的分配。


    try:
        result = await Recomendations.find_one({"_id": PydanticObjectId(recomendation_id)})
        if not result:
            raise HTTPException(status_code=404, detail="Recomendation not found")

        await result.update(
            {
                "$set": {
                    "artist_recomendations.$[x].approve": datetime.now(),
                    "artist_recomendations.$[x].notes": artist_recomendation.notes,
                    "artist_recomendations.$[x].feedback": artist_recomendation.feedback,
                },
            },
            array_filters=[{"x.artist": DBRef(collection=('artists'), id=artist_id)}], 
        )
        return result
    except Exception as e:
        print(e)
        raise HTTPException(status_code=404, detail="Item not found")
    
© www.soinside.com 2019 - 2024. All rights reserved.