[英]MongoDB shell: How to remove specific elements in all the collections inside a DB
我想在所有集合中刪除與regex表達式的所有巧合。
我需要這樣做,因為今天某時某個應用程序中的JSON解析器失敗了,現在數據庫已損壞。
我可以手動完成,但是我有100多個集合,並手動輸入mongo shell db["X"].remove({ "DateTime": { $regex : "2015-11-16" } })
每個集合將花費很多時間。
您知道在mongo shell中自動執行此操作的任何方法嗎? 我總是通過R中的RMongo
軟件包訪問該數據庫,我可以通過dbRemoveQuery(rmongo.object, collection, query)
但是我想知道是否可以在mongo shell中完成,也許更快一些。
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" } });
}
}
請注意,我從列表中排除了系統集合 。
在mongo shell中:
db.getCollectionNames().forEach(function(name) {
db[name].remove({ "DateTime": { $regex : "2015-11-16" } });
})
那么.startsWith()
是一項新技術,屬於ECMAScript 2015(ES6)標准的一部分,因此它可能無法在Mongo Shell中使用。
您將需要使用.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/ } )
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.