Is there a way to delete all collections in a database except the one ? nodejs mongodb, mongoose


I am having multiple collections inside a single database. I have basically created collections name by current date like 20220829, 20220830, 20220831 (these are collection names). I want to keep only 20220831 collection (the latest one) and basically delete all others in that database. Is there a way to do this optimally?


Please refer following code snip

afterEach(async function () {

var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

let todaysDate = yyyy+mm+dd

const collections = await mongoose.connection.db.collections()

  for (let collection of collections) {
    if(collection !== todaysDate)
    await collection.remove();

Answered By – Karan Chokshi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published