I've restructured my database a bit, and no longer have need for certain collections. However, there are far too many of them to remove by-hand (thousands, actually). Each of the collections in question begins with "cache_" and contains a couple of indexes which I'd like to make sure are completely cleaned up.
I'm trying to understand how to use the mongo shell in order to loop over all collection names and remove those collections which begin with "cache_". Per the Queries & Cursors documentation, I understand how to loop over documents within a collection, but not how to use the MongoDB shell to loop through the collections in the database.
In pseudo-code, this is what I need:
var all_collections = show collections
for(var collection in all_collections)
if(collection.name.indexOf('cache_')==0)
collection.drop()
FWIW, I've done searching for "mongodb loop through collection names" etc. and have not found anything, but maybe I sux at teh googlez =P
On a related note... after doing this degree of restructuring, should I be doing a db.repairDatabase()
or anything of the sort in order to make sure the dropped indexes etc. are all nice and clean?
Thanks.
In MongoDB, you are allowed to delete the existing documents from the collection using db. collection. deleteMany() method. This method deletes multiple documents from the collection according to the filter.
drop() will delete to whole collection (very fast) and all indexes on the collection.
Yes, to all.
Use db.getCollectionNames()
to get the all the collections and store them in an array.
var collectionNames = db.getCollectionNames();
for(var i = 0, len = collectionNames.length; i < len ; i++){
var collectionName = collectionNames[i];
if(collectionName.indexOf('cache_') == 0){
db[collectionName].drop()
}
}
Just to add another answer found on mongodb mailing list
db.adminCommand("listDatabases").databases.forEach( function (d) {
if (d.name != "local" && d.name != "admin" && d.name != "config")
db.getSiblingDB(d.name).dropDatabase();
})
You probably want to not drop the local/config/admin dbs as I've listed above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With