我是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}})
感谢您在指导我解决此问题方面的帮助。谢谢你。
答案 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}})