我正在使用pymongo,并且我有一个用户集合。用户实例类似于:
user = {"Email":"user@gmail.com" , "Comments":["Good" , "Bad" , " Very bad "] }
我正在尝试按索引删除Comments[]字段中的元素(例如。index =0 delete "Good")我将索引与输入数字相同的注释设置为"deleted“,然后拉出它,因为我正在迭代特定用户的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
如果您能帮助我解决这个错误,我将不胜感激。提前谢谢你
发布于 2020-06-21 12:42:50
从MongoDB v4.2开始,不能使用$set
直接指向给定索引处的数组,也不能使用$pull
删除给定索引处的元素。
从v4.2开始,您可以做的是使用update with aggregation pipeline将数组更新为指定索引前后的数组元素的串联。
因此,如果您有i = 0
,那么它将是[]
和["Bad" , " Very bad "]
的串联
如果您有i = 1
,那么它将是["Good"]
和[" Very bad "]
的串联
我们可以使用$concatArrays
和$slice
users.update_one(
{ "Email": email } ,
[{ // specify update as an array to use the pipeline update
"$set": {
"Comments": {
"$concatArrays": [
{ "$slice": ["$Comments", i] }, // keep i elements from the start of the array
{ "$slice": ["$Comments", i+1, { "$size": "$Comments" } ] } // keep element from i+1 to the end of the array
]
}
}
}]
)
提示:如果想要删除第一个或最后一个数组元素,可以使用$pop
发布于 2020-06-21 14:06:35
修正:比我想象的要简单得多,也没那么复杂。
comment_num = int(comment_num)
exists = False
for i , value in enumerate(usr['Comments']):
if i+1 == comment_num:
print("Comment number exists")
exists = True
users.update_one({"Email":email} ,
{"$pull":{"Comments":value}})
elif i+1 == len(usr['Comments']) and exists == False:
print('Comment does not exist')
https://stackoverflow.com/questions/62498176
复制