14

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.

  • I think your question is duplicated -> see http://stackoverflow.com/questions/10146735/deleting-a-key-value-from-existing-mongodb-entry – devasia2112 Aug 14 '15 at 05:19
  • try to `pull` like this `update({},{"$pull":{"list":"four"}})` – Neo-coder Aug 14 '15 at 05:22
  • possible duplicate of [Removing specific items from array with MongoDB](http://stackoverflow.com/questions/9048424/removing-specific-items-from-array-with-mongodb) – Blakes Seven Aug 14 '15 at 05:40

1 Answers1

23

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" ] } } }
});
hisener
  • 1,431
  • 1
  • 17
  • 23
Yathish Manjunath
  • 1,919
  • 1
  • 13
  • 23