Search code examples
javascriptmongodbmongodb-querymongodb-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.

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.


Solution

  • 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.