4

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."
    }
})
6
  • How are you defining an "empty field" in your question? Can you edit your question to provide an example? Commented Jun 5, 2014 at 18:50
  • The key is literally "" Commented Jun 5, 2014 at 18:57
  • Interesting...I didn't even know that was possible. Commented Jun 5, 2014 at 19:15
  • 2
    I believe this is the relevant bug: jira.mongodb.org/browse/SERVER-12996 Commented Jun 5, 2014 at 19:41
  • I have the exact same problem. How was this solved? The accepted answer does not work in latest MongoDB Commented Jul 12, 2016 at 21:04

4 Answers 4

5

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);
});
Sign up to request clarification or add additional context in comments.

Comments

4

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 }})

Comments

2

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

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

Comments

0

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})
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.