根据元素的位置删除mongoDB中的数组元素 [英] Removing the array element in mongoDB based on the position of element
问题描述
实际上我需要根据它的位置从数组中删除一个元素.使用 $pop 我们可以从顶部或底部删除元素(将其视为堆栈.顶部的第 0 个元素),如 此处.
Actually I need to remove an element from the array based on its position. Using $pop we can remove element from top or bottom (considering it as a stack. 0th element at top) as explained here.
我们也可以使用 $pull 根据数组中元素的值从数组中删除元素,如这里.
We can also remove element from array based on the value of the elements in the array using $pull as explained here.
但我需要根据位置从数组中删除元素.那么我有什么办法可以做到这一点.
But I need to remove element from the array based on position. So is there any way I can do this.
推荐答案
来自文档:
{ $pull : { field : {$gt: 3} } } removes array elements greater than 3
所以我想你现在可以做这样的事情:
So i suppose that you can do somethig like this for now:
{ $pull : { field : {$gt: 3, $lt: 5} } } // shoud remove elemet in 4 position
或者尝试使用位置运算符进行更新,我想应该是这样的:
Or try update using position operator, i suppose shoud be something like this:
{ $pull : "field.4" }
{ $pull : {"field.$": 4}}
这只是一个建议,因为我现在无法测试.
It is only a suggestion, because i can't test it right now.
更新:
似乎你不能一步做到正确(有这样的 jira 中的错误)
Seems you cant do it right know in one step(there is such bug in jira)
但是您可以使用 unset 元素在 position 中移除并使用空值拉动元素:
But you can remove using unset element in position and that pull elemets with null value:
{$unset : {"array.4" : 1 }}
{$pull : {"array" : null}}
这篇关于根据元素的位置删除mongoDB中的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!