0

As I know how to clone the MongoDB collection by typing the command on cmd. As I want to do clone through javascript which will be running through cron job on nodejs environment.

Like on my app.js file I am calling the file like this
var Message = require('./models/copymessage');

what I would like is like this

var CopyCollection = new CronJob('00 36 17 * * *', function() {
    //Some command which can copy the collection.
    //I am using MongoDB 3.0+ version
}, null, true, 'Asia/Kolkata');

Any help is appreciated

1 Answer 1

3

I assume that you want to copy a collection within the same MongoDB instance

There is an implementation that I use. You can skip the lines with indexes if you don't want to copy it.

function copyCollection(from, to) {
    db.getCollection(from).aggregate([ { $out: to } ])
    db.getCollection(from).getIndexes().forEach(function(inx) {
         db.getCollection(to).createIndex(inx.key);
    })
    var newCollectionDocuments = db.getCollection(to).count()
    var newCollectionIndexes = db.getCollection(to).getIndexes()
    print("Document inserted: " + newCollectionDocuments)
    print("Indexes: " + tojson(newCollectionIndexes))
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.