Home > OS >  MongoDB shell: how to remove all collections except list
MongoDB shell: how to remove all collections except list

Time:01-14

I would like to remove all collections except a list.

db.getCollectionNames().forEach(function(n){db[n].remove({})});

will remove all collections.

db.getCollectionNames().filter(function(collection){return! /^((keepthisone)|(andthisone)|(alsokeepthisone))$/.test(collection)});

will list all the collections, except the ones I want to keep.

How do I combine the two?

db.getCollectionNames().filter(function(collection){return! /^((keepthisone)|(andthisone)|(alsokeepthisone))$/.test(collection)}).forEach(function(n){db[n].remove({})});

Does nothing.

CodePudding user response:

I would map then drop on items :

db.getCollectionNames().filter(function(collection) {
    return !/^((keepthisone)|(andthisone)|(alsokeepthisone))$/.test(collection);
}).map(function(n){
    return db.getCollection(n);
}).forEach(function(collection){
    collection.drop();
});

CodePudding user response:

I would prefer this:

db.getSiblingDB('test').getCollectionNames().filter( 
   collection => !['keepthisone', 'andthisone', 'alsokeepthisone'].includes(collection)
).forEach( collection => {
    db.getSiblingDB('test').getCollection(collection).drop();
});

You should use getSiblingDB(...) for security reasons. You never know if the user executed stupid command like use admin before running yours. The result would be rather bad.

  • Related