如何在MongoDB中删除数组的第n个元素 [英] How to delete n-th element of array in mongodb
问题描述
例如,我有此文档:
db.test.save({
_id: 1,
list: [
{ key: "a" },
{ key: "b" },
{ key: "c" },
{ key: "d" },
{ key: "e" }
]
})
我需要从列表中删除第二个元素.
and I need remove to the second element from the list.
目前,我分两个步骤进行操作.我首先取消设置第二个列表元素,但是$unset
运算符不会删除该元素,而是将其修改为null
,然后我从列表字段中拉出任何可为空的值:
For now I do that in two steps. I first unset the second list element but the $unset
operator doesn't remove the element, it modifies it to null
, and after that I pull any nullable value from the list field:
db.test.update({_id: 1}, {$unset: {"list.2": 1}})
db.test.update({_id: 1}, {$pull: {list: null}})
有一种解决方案可以一次完成吗?
Is there a solution to do that in one operation?
推荐答案
否,不幸的是,您目前正在做的是最好的选择.看一下这个问题:在mongoDb中,如何通过其索引删除数组元素,该元素链接到Jira,这个问题.
No, unfortunately what you are doing is currently the best option. Have a look at this question: In mongoDb, how do you remove an array element by its index which links to a Jira for this very issue.
这篇关于如何在MongoDB中删除数组的第n个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!