由于客户端代码中的错误,mongodb 创建了许多“mr.mapreduce ....”集合,如何将它们全部删除(可能通过掩码)。
4 回答
我在交互式 shell 中运行脚本:
function f() {
var names = db.getCollectionNames();
for(var i = 0; i < names.length; i++){
if(names[i].indexOf("mr.") == 0){
db[names[i]].drop();}}};
f();
它解决了我的问题。
Temporary map-reduce table should be cleaned up when the connection which created them is closed:
map/reduce is invoked via a database command. The database creates a temporary collection to hold output of the operation. The collection is cleaned up when the client connection closes, or when explicitly dropped. Alternatively, one can specify a permanent output collection name. map and reduce functions are written in JavaScript and execute on the server.
-- MongoDB docs
If not, you could delete them using them same method you would delete any other collection. It might get a bit repetitive though.
实现相同目的的另一种方法是这个片段:
db.system.namespaces.find({name: /tmp.mr/}).forEach(function(z) {
try{
db.getMongo().getCollection( z.name ).drop();
} catch(err) {}
});
优点:它不会尝试将所有命名空间收集到 JavaScript 数组中。MongoDB 在太多命名空间上的段错误。
当创建它们的连接关闭时,应清理临时 map-reduce 集合。但是有时它们会保留在那里并增加数据库大小。您可以使用以下脚本删除它们:
var database = db.getSiblingDB('yourDatabaseName');
var tmpCollections = database.getCollectionInfos(
{
name: {$regex: /tmp\.mr*/},
'options.temp': true,
});
tmpCollections.forEach(function (collection) {
database.getCollection(collection.name).drop();
});
print(`There was ${tmpCollections.length} tmp collection deleted`);
该drop.tmp.js
脚本可以从命令行执行,如下所示:
mongo --quiet mongodb://mongodb:27137 drop.tmp.js