2

https://mongoplayground.net/p/Yv6vkGyrUS-

https://mongoplayground.net/p/vm314GoexjE

[
 {
   "_id": ObjectId("4b253b067525f35f94b60a31"),
  "age": 30,
  "favorite book": [
  "Cat's Cradle",
  "Foundation Trilogy",
  "Ender's Game"
   ],
"location": "Wisconsin",
"name": "joe",
"sex": "male"
}
]

output delete any element with based on condition

"favorite book": [
  "Cat's Cradle",
  "Foundation Trilogy"
   ]
suresh
  • 31
  • 5

1 Answers1

1

You can use $pull operator

db.collection.update({
    { _id : id },
    { $pull: { "favorite book": "Ender's Game" } }
});

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: { "favorite book" : { $in : [ "Foundation Trilogy", "Ender's Game"] } } }
});

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

script0
  • 387
  • 2
  • 12
  • its possible with unset ? – suresh Dec 16 '21 at 06:48
  • Yes. I think. But You will use the index of the element. But, it doesn’t remove the array element. Instead, it sets it to null. Check out https://www.mongodbtutorial.org/mongodb-crud/mongodb-remove-field-unset/ – script0 Dec 16 '21 at 07:09