mongodbmongodb-querydatabase

How to remove a field from all documents in a MongoDB collection


Suppose this is a document I have in a collection:

{ 
    name: 'book',
    tags: {
        words: ['abc','123'],
        lat: 33,
        long: 22
    }
}

How do I remove "words" completely from all the documents in this collection? I want all documents to be without "words":

 { 
     name: 'book',
     tags: {
         lat: 33,
         long: 22
     }
}

Solution

  • You would use $unset for this. For example, if your collection is named example, this will remove the words array from the first document that matches your criteria.

    db.example.update({}, {$unset: {"tags.words":1}});
    

    If you want to apply .update() to all documents in the collection, then you need to [include the {multi: true} option:

    db.example.update({}, {$unset: {"tags.words":1}}, {multi: true});
    

    Alternatively, instead of .update(), it's recommended today to use updateMany(), which internally calls update() and includes {multi: true}: (References: Release notes, GitHub code repository):

    db.example.updateMany({}, {$unset: {"tags.words":1}});
    

    Regardless, using any of the preceding commands will result in the following modified collection object(s):

    { 
        name: 'book',
        tags: {
            lat: 33,
            long: 22
        }
    }