Jonathan
Jonathan

Reputation: 8900

Removing empty fields from MongoDB

Normally you would use the following to remove a field from a collection. However the code below does not work for empty ("") fields. How would you go about deleting an empty field in MongoDB?

db.collection.update({}, {$unset: {"": ""}}, {multi:true})

I get the following error message when I try this:

WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 56,
        "errmsg" : "An empty update path is not valid."
    }
})

Upvotes: 4

Views: 7588

Answers (4)

I.Blair
I.Blair

Reputation: 591

Updated for mongodb version 4.2+ (db.collection.save is no longer supported)

Empty field keys aren't fully supported by mongodb, and look like they are going to be depreciated.

To get rid of empty field keys

db.collection.find({"":{$exists:true}).forEach(
    (doc)=>{
       delete doc[""];  
       db.collection.replaceOne(doc,doc,{upsert:true})
})

Upvotes: 0

Roman
Roman

Reputation: 21883

If you need to delete rows with the field, that is empty, you can use:

db.collection.deleteMany({ 'myField': null})

Upvotes: 2

J.C. Gras
J.C. Gras

Reputation: 5442

To do this using the update or updateMany method, you must specify the parameter you want to update, such as name:

db.collection.updateMany({name: ""}, { $unset : { name : 1 }})

Upvotes: 5

JohnnyHK
JohnnyHK

Reputation: 312179

It looks like empty string keys must only be partially supported by MongoDB.

This isn't as efficient as a multi-update, but it does work to remove those fields in the shell:

db.collection.find().forEach(function(doc) {
    delete doc[''];
    db.collection.save(doc);
});

Upvotes: 5

Related Questions