簡體   English   中英

MongoDB:使用pymongo刪除一個集合中多個文檔中的數組值

[英]MongoDB: deleting an array value in multiple documents in one collection using pymongo

下午大家。 我希望你能幫助解決一個問題。 我正在使用創建 Flask 應用程序並使用 pymongo,我需要從一個集合中多個文檔的多個數組中刪除單個數組值。 我在“食譜”集合中有食譜文檔,每個文檔中都有一個數組(“類別”),長度可以在 1 到 3 個值之間。 我在我的網站的管理部分中有一個可用的功能,它允許從“類別”集合中刪除一個類別,因此,為此,我想刪除“類別”數組中該類別值的任何實例在食譜“集合”中的任何食譜文檔上。

我已經成功地在一個文件上做到了這一點:

mongo.db.recipes.update(
        {"_id": ObjectId("60df2eec9df14e58d0c698c8")},
        {"$pull": {"category": category_id}}
    )

但還沒有在整個集合上管理這個我已經確定我需要使用'update_many'查詢在集合上使用 $all 和 $pull 運算符,並且到目前為止已經嘗試過:

mongo.db.recipes.update_many({"category": {"$all": {"$pull": {"category": category_id}}}})

mongo.db.recipes.update_many({"$all": {"$pull": {"category": category_id}}})

mongo.db.recipes.update_many({"category": {"$pullAll": {"category": category_id}}})

他們都沒有工作。 我不斷收到錯誤:

TypeError: update_many() missing 1 required positional argument: 'update'

任何幫助,將不勝感激。

閱讀 - https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html?highlight=update_many#pymongo.collection.Collection.update_many

第一個參數是過濾器,如果您想更新所有文檔,它將是{}

mongo.db.recipes.update_many(
  {} // filter filter,
  {} // update
)

mongo.db.recipes.update_many({ }, {"$pull": {"category": category_id}})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM