删除满足条件的MongoDB集合中的所有文档

时间:2020-06-20 10:56:56

标签: python mongodb collections pymongo

我是pymongo和flask的初学者,并且我有一个用户集合,其中包含一个用户实例:

user = { "Email" : "user@gmail.com" , "Comments" : ["good user", "bad user "] }

我想遍历我的users集合,并且如果每个用户的Comment数组中的任何字符串包含单词“ good”,我都想删除特定的comment。但是我是一个初学者,我不太了解pymongo语法来做到这一点。在我的代码下方,不会删除任何现有注释:

                i = users.find()
                for customer in i: #for every user in collection 
                    for comment in customer['Comments']:  #for every comment in the comments field
                        if "good" in comment:
                            print("comment found") #if comment is found print this 
                            users.update_one( {"Comments": "good"} , {"$pull": {"Comments": comment}})

感谢您在指导我解决此问题方面的帮助。谢谢你。

1 个答案:

答案 0 :(得分:0)

已解决:

                     i = users.find()
                    for customer in i:
                        for comment in customer['Comments']:
                            if "good" in comment:
                                print(comment) 
                                users.update_one( {"Comments": comment } ,
                                {"$pull": {"Comments": comment}})