60

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!

Sergio Tulentsev
  • 219,187
  • 42
  • 361
  • 354
Chris
  • 1,385
  • 1
  • 17
  • 36
  • 2
    Possible duplicate of [How do I remove a field completely from Mongo?](http://stackoverflow.com/questions/6851933/how-do-i-remove-a-field-completely-from-mongo) – Frank Tan Oct 13 '16 at 18:18

3 Answers3

130

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} })
Jason Sperske
  • 28,710
  • 8
  • 67
  • 121
Bee San
  • 2,395
  • 2
  • 17
  • 19
  • 17
    To update all documents in a collection you can use: `db.collection_name.update({}, {$unset: { description:1}}, false, true);` The last true is for multiple documents update – Gilad Peleg Sep 16 '13 at 09:33
  • 3
    Newer versions support a more readable format: `db.example.update({},{$unset: {words:1}}, {multi: true})` – phocks Jul 04 '16 at 01:00
  • 2
    to update all documents, you can use updateMany instead of update like this ````db.collection_name.updateMany({}, { $unset : { description : 1} })```` – vikneshwar May 01 '18 at 12:30
  • 1
    What 1 does here? I mean mentioning just the key name seems to be enough. 1 is not making any specific meaning if there is no -1. Is there any possibility to have -1 as well along with "description" key? – Irfan Raza Sep 24 '18 at 09:36
  • Saved my time :) Thanks Bee San – Joe Sep 16 '21 at 00:29
  • @IrfanRaza 1 does not affect the operation, we can put anything there. – Navitas28 May 16 '22 at 13:36
4

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" } )]
taskinoor
  • 44,735
  • 12
  • 114
  • 137
aspadacio
  • 313
  • 2
  • 11
-9

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.

Adrien M.
  • 313
  • 1
  • 3
  • 9