0

I would like to remove, in all collections, all coincidences with a regex expression.

I need this, because a JSON parser failed in my app at a certain point today, and now the database is corrupted.

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.

Do you know any way to perform this automatically inside 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.

styvane
  • 59,869
  • 19
  • 150
  • 156
Geiser
  • 1,054
  • 1
  • 12
  • 28

3 Answers3

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" } });
    }
}

Please note that I am excluding system collections from the list.

Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67
2

In mongo shell:

 db.getCollectionNames().forEach(function(name) {
     db[name].remove({ "DateTime": { $regex : "2015-11-16" } });
 })
Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67
SalaryNotFound
  • 224
  • 1
  • 8
1

Well .startsWith() is a new technology, part of the ECMAScript 2015 (ES6) standard so it may not work in Mongo Shell.

You will need to use the .filter() method to discard system collections

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"

for(var index=0; index < collections.length; index++) {
    db[collections[index]].remove( { 'DateTime': /2015-11-16/ } )
}
styvane
  • 59,869
  • 19
  • 150
  • 156