2015-11-16 92 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/ }) 
} 
相關問題