Reputation: 167
I've been able to add a large volume of empty keys in a MongoDB collection. As empty keys is not allowed in MongoDB I'm having a hard time to unset the key using regular methods in MongoDB. Is there a workaround for this kind of problems using mongo shell?
{
"foo": "bar",
"": "I should not exist, I have no key..."
}
Upvotes: 5
Views: 1699
Reputation: 42362
If you are on version 5.0 or later, you can use $setField
expression with expressive pipeline update:
db.c.updateMany({ "": { "$exists": true } },
[ {$replaceWith:{$setField:{field:"",input:"$$ROOT",value:"$$REMOVE"}}}]
)
If you are on 4.2 through 4.4 (pre-5.0) you can do it with different pipeline update:
db.c.updateMany({ "": { "$exists": true } },
[ {$replaceWith:{$arrayToObject:{$filter:{
input:{$objectToArray:"$$ROOT"},
cond:{$ne:["$$this.k",""]}
}}}}]
)
Upvotes: 1
Reputation: 61293
We can delete the empty string field using bulk operations.
We need to iterate over the cursor snapshot then use the bulkWrite
method method to bulk update the document. Note that we need to replace the document because we can't $unset
the empty field or rename it. So an update operation is not possible here.
let requests = [];
db.coll.find( { "": { "$exists": true } } ).snapshot().forEach( document => {
delete document[""];
requests.push( {
"replaceOne": {
"filter": { "_id": document._id },
"replacement": document
}
});
if ( requests.length === 1000 ) {
// Execute per 1000 operations and re-init
db.coll.bulkWrite(requests);
requests = [];
}
});
// Clean up queues
if ( requests.length > 0 ) {
db.coll.bulkWrite(requests);
}
Upvotes: 4
Reputation: 243
Give this a throw....
db.collection.find().forEach(function(doc) {
delete doc[''];
db.collection.save(doc);
});
There are some abilities to manage documents that have errors in them, such as empty keys.
Upvotes: 1