skip to Main Content

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.

2

Answers


  1. 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();
    });
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search