如何在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屋!