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.
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 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];
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.
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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With