【发布时间】:2020-06-21 11:56:09
【问题描述】:
我正在使用 pymongo 并且我有一个 users 集合。一个用户实例是这样的:
user = {"Email":"user@gmail.com" , "Comments":["Good" , "Bad" , " Very bad "] }
我正在尝试按索引删除 Comments[] 字段中的元素(例如 index = 0 delete "Good") 我将索引与输入编号相同的注释设置为“已删除”,然后将其拉出 但是,由于我正在为特定用户迭代 Comments[] 数组,我得到了错误
pymongo.errors.WriteError: Cannot create field 'i+1' in element
我不明白为什么。 我的代码:
comment_num = int(comment_num) #an index I have as input
exists = False #we will check if index exists in list
for i , value in enumerate(usr['Comments']):
if i+1 == comment_num: #if index is comment_num
print("Comment number exists")
exists = True
#I get the error here
users.update_one({"Email":email} , {"$set" : {"Comments.i+1" : "deleted" } } )
users.update_one({"Email":email} , {"$pull":{"Comments":"deleted" }})
elif i+1 == len(usr['Comments']) and exists == False:
print('Comment does not exist') #if index not found
感谢您帮助指导我解决此错误。提前谢谢你
【问题讨论】: