Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing the array element in mongoDB based on the position of element

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.

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.

like image 875
aditya_gaur Avatar asked Feb 11 '11 13:02

aditya_gaur


People also ask

How do I remove a specific element from an array in MongoDB?

To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

How do I remove an element from a specific position?

How to remove an element at a specific position or index from an array in JavaScript? To remove elements or items from any position in an array, you can use the splice() array method in JavaScript. Consider this array of numbers, // number array const numArr = [23, 45, 67, 89];

How do you remove an item from an array?

If you want to remove an item from an array, you can use the pop() method to remove the last element or the shift() method to remove the first element.


1 Answers

From documentation:

{ $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.

Update:

Seems you cant do it right know in one step(there is such bug in jira)

But you can remove using unset element in position and that pull elemets with null value:

{$unset : {"array.4" : 1 }}
{$pull : {"array" : null}}
like image 66
Andrew Orsich Avatar answered Oct 01 '22 00:10

Andrew Orsich