Deleting a key/value from existing MongoDB entry

Mongodb

Mongodb Problem Overview


I need to delete a certain key and value from every entry in a particular collection. I've looked into remove and that seems to be for only entire entries. Looking at update, I don't believe updating a particular key with null or an empty string would achieve what I'm trying to do. I'm very much a beginner with mongodb, so please excuse my ignorance.

Long story short, how can I turn

{
  "_id" : 1234,
  "name" : "Chris",
  "description" : "Awesome"
}

into

{
  "_id" : 1234,
  "name" : "Chris"
}

without deleting the entry and creating a new one, or using any non-mongodb commands? Thanks!

Mongodb Solutions


Solution 1 - Mongodb

Try $unset in a call to update().

Like this:

db.collection_name.update({ _id: 1234 }, { $unset : { description : 1} })

And, as vikneshwar commented, if you want to remove one field from all (or multiple) documents you can use updateMany() like this:

db.collection_name.updateMany({}, { $unset : { description : 1} })

Solution 2 - Mongodb

To reference a package and remove various "keys", try this

db['name1.name2.name3.Properties'].remove([ { "key" : "name_key1" }, { "key" : "name_key2" }, { "key" : "name_key3" } )]

Solution 3 - Mongodb

Also think about upsert() that will insert your row as a new document if _id does not exist or update the existing document if any.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChrisView Question on Stackoverflow
Solution 1 - MongodbBee SanView Answer on Stackoverflow
Solution 2 - MongodbaspadacioView Answer on Stackoverflow
Solution 3 - MongodbAdrien M.View Answer on Stackoverflow