Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove a string from an array in a mongodb document?

Tags:

mongodb

I've been having trouble with the problem of removing a string from an array in a mongodb document. For example I want to remove the entry "four" from the list field in the document below.

{
  "list" : [ "1", "2", "four", "five", "6"]
}

I know it seems very simple but I haven't been able to find a straight answer from the docs or previous questions. I've tried 5 or so commands to no avail using db.collection.update combined with the $pull and $mod modifiers. Any help?

I know, very rudimentary question.

like image 359
Ethan Wilberforce Avatar asked Aug 14 '15 05:08

Ethan Wilberforce


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 edit an array in MongoDB?

You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.


1 Answers

You can use $pull operator, please try the below query:

db.collection.update({
    { _id : id },
    { $pull: { "list": "four" } }
});

If you want to remove two or more elements from the array "list", you can do that with $pull operator, as well:

db.collection.update({
    { _id : id },
    { $pull: { list : { $in : [ "one", "four" ] } } }
});
like image 168
Yathish Manjunath Avatar answered Sep 28 '22 10:09

Yathish Manjunath