Search code examples
mongodbmongodump

Mongo dump for a collection on a specific date


I want to take the backup of a specific collection for a specific date.

My use case is : I have to take the backup of data that are older than 90 days and then delete them from the collection.


Solution

  • One solution is to get 90th day from today. And apply that into mongodump using --query=<json> which accepts json documents as query params.

    const today = new Date();
    const todayMillis = today.getTime();
    
    /*90th past day from today*/
    const nthDayfromToday = todayMillis - (90 * 24 * 60 * 60 * 1000);
    console.info(nthDayfromToday); //Lets say this is 1586450232676

    Create a file query.json with contents- use the timestamp calculated above:

    { "createdAt": { "$lt": { "$date": 1586450232676 } } }
    

    Run mongodump command:

    mongodump --db <dbname> --collection <collection> --queryFile query.json