Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete n-th element of array in mongodb

Tags:

arrays

mongodb

For example I have this document:

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.

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?

like image 401
Denis Dubinin Avatar asked Aug 29 '11 08:08

Denis Dubinin


People also ask

How do I remove an 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 you remove the nth element from an array?

Use Array#splice method to remove an element from the array. Where the first argument is defined as the index and second as the number elements to be deleted. To remove elements at 3rd position use a while loop which iterates in backward and then delete the element based on the position.


1 Answers

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.

like image 161
Russell Avatar answered Sep 30 '22 14:09

Russell