简体   繁体   English

MongoDB Shell:如何删除数据库内所有集合中的特定元素

[英]MongoDB shell: How to remove specific elements in all the collections inside a DB

I would like to remove, in all collections, all coincidences with a regex expression. 我想在所有集合中删除与regex表达式的所有巧合。

I need this, because a JSON parser failed in my app at a certain point today, and now the database is corrupted. 我需要这样做,因为今天某时某个应用程序中的JSON解析器失败了,现在数据库已损坏。

I could do it by hand, but I have over 100+ collections, and manually entering in mongo shell db["X"].remove({ "DateTime": { $regex : "2015-11-16" } }) for each collection would take quite a few time. 我可以手动完成,但是我有100多个集合,并手动输入mongo shell db["X"].remove({ "DateTime": { $regex : "2015-11-16" } })每个集合将花费很多时间。

Do you know any way to perform this automatically inside mongo shell? 您知道在mongo shell中自动执行此操作的任何方法吗? I always access this database via package RMongo in R, and I could do it via dbRemoveQuery(rmongo.object, collection, query) but I was wondering if it could be done inside mongo shell, maybe a little quicker. 我总是通过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" } });
    }
}

Please note that I am excluding system collections from the list. 请注意,我从列表中排除了系统集合

In mongo shell: 在mongo shell中:

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

Well .startsWith() is a new technology, part of the ECMAScript 2015 (ES6) standard so it may not work in Mongo Shell. 那么.startsWith()是一项新技术,属于ECMAScript 2015(ES6)标准的一部分,因此它可能无法在Mongo Shell中使用。

You will need to use the .filter() method to discard system collections 您将需要使用.filter()方法来丢弃系统集合

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

Then remove the documents that match you criteria here where "DateTime": "2015-11-16" 然后在此处的"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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM