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.
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.
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.
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" ] } } }
});
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