2015-11-16 86 views
0

我想在所有集合中删除与正则表达式的所有重合。MongoDB shell:如何删除数据库中所有集合中的特定元素

我需要这个,因为JSON解析器在今天的某个时间点在我的应用程序中失败,现在数据库已损坏。

我可以手工做到这一点,但我有超过100多个系列,并且手动输入蒙戈壳 db["X"].remove({ "DateTime": { $regex : "2015-11-16" } })对于每个集合都需要很长时间。

你知道有什么方法可以在mongo shell内自动执行吗?我总是通过R中的包RMongo来访问这个数据库,我可以通过dbRemoveQuery(rmongo.object, collection, query)来完成,但我想知道它是否可以在mongo shell内部完成,也许更快一点。

回答

2
use yourDbName 

// Get the names of all collections in the database. 
var names = db.getCollectionNames(); 

// Iterate over every collection name. 
for(i = 0; i < names.length; i++) { 

    // Only issue the query if the collection is not a system collection. 
    if(!names[i].startsWith("system.")) { 

     // Issue the query against the collection with the name `names[i]`. 
     db[names[i]].remove({ "DateTime": { $regex : "2015-11-16" } }); 
    } 
} 

请注意,我从列表中排除system collections

2

在蒙戈外壳:

db.getCollectionNames().forEach(function(name) { 
    db[name].remove({ "DateTime": { $regex : "2015-11-16" } }); 
}) 
+0

感谢您的努力,但(没有文件知道为什么),表现不佳。 –

+0

@Sergio我已经解决了这个问题。现在它也会起作用。 –

+0

谢谢,但它没有问题''',我把它放在失败后,但之后,我检查收集和文件仍然存在。 –

1

.startsWith()是一项新技术,在2015年的ECMAScript(ES6)标准,所以它可能不会在蒙戈壳牌工作的一部分。

您将需要使用.filter()方法丢弃系统集合

var collections = db.getCollectionNames().filter(function(collection) { 
    return collection.indexOf('system.') !== -1; 
}; 

然后删除符合您在这里标准的地方"DateTime": "2015-11-16"

for(var index=0; index < collections.length; index++) { 
    db[collections[index]].remove({ 'DateTime': /2015-11-16/ }) 
} 
相关问题