我已經能夠在MongoDB集合中添加大量的空鍵。由於MongoDB中不允許空鍵,所以我很難在MongoDB中使用常規方法取消鍵。有使用mongo shell的這種問題的解決方法嗎?從文檔中刪除空字段的名稱
{
"foo": "bar",
"": "I should not exist, I have no key..."
}
我已經能夠在MongoDB集合中添加大量的空鍵。由於MongoDB中不允許空鍵,所以我很難在MongoDB中使用常規方法取消鍵。有使用mongo shell的這種問題的解決方法嗎?從文檔中刪除空字段的名稱
{
"foo": "bar",
"": "I should not exist, I have no key..."
}
我們可以使用批量操作刪除空字符串字段。
我們需要迭代光標快照,然後使用bulkWrite
方法方法批量更新文檔。請注意,我們需要替換文檔,因爲我們不能在$unset
空白字段或重命名它。所以更新操作在這裏是不可能的。
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);
}
這是切肉刀! – user1885523
給這個一拋....
db.collection.find().forEach(function(doc) {
delete doc[''];
db.collection.save(doc);
});
有一些能力來管理在他們的錯誤,如空鍵文件。
不要這樣做!這對性能不利。他們是更好的方式來「解除」該領域。 – styvane
請提供更好的解決方案。謝謝。 – arcee123
Thx的想法。這會在我的MongoDB shell版本中觸發錯誤:3.2.5 E QUERY [thread1] SyntaxError:missing]在元素列表之後: – user1885523
您在每個文檔中有多少個字段? – styvane
每個文件大約20場 – user1885523