mongodbmongodb-querydatabase

How to remove a field completely from a MongoDB document?


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

Suppose this is a document. 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

  • Try this: If your collection was 'example'

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

    Refer this:

    http://www.mongodb.org/display/DOCS/Updating#Updating-%24unset

    UPDATE:

    The above link no longer covers '$unset'ing. Be sure to add {multi: true} if you want to remove this field from all of the documents in the collection; otherwise, it will only remove it from the first document it finds that matches. See this for updated documentation:

    https://docs.mongodb.com/manual/reference/operator/update/unset/

    Example:

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