In the following example, assume the document is in the db.people collection.
How to remove the 3rd element of the interests array by it's index?
{ "_id" : ObjectId("4d1cb5de451600000000497a"), "name" : "dannie", "interests" : [ "guitar", "programming", "gadgets", "reading" ] }
This is my current solution:
var interests = db.people.findOne({"name":"dannie"}).interests; interests.splice(2,1) db.people.update({"name":"dannie"}, {"$set" : {"interests" : interests}});
Is there a more direct way?
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.
Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.
To remove an array element at index i, you shift elements with index greater than i left (or down) by one element. For example, if you want to remove element 3, you copy element 4 to element 3, element 5 to element 4, element 6 to element 5.
There is no straight way of pulling/removing by array index. In fact, this is an open issue http://jira.mongodb.org/browse/SERVER-1014 , you may vote for it.
The workaround is using $unset and then $pull:
db.lists.update({}, {$unset : {"interests.3" : 1 }}) db.lists.update({}, {$pull : {"interests" : null}})
Update: as mentioned in some of the comments this approach is not atomic and can cause some race conditions if other clients read and/or write between the two operations. If we need the operation to be atomic, we could:
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