21

What is the best way to execute mongodb admin/console commands programmatically from node.js? Specifically, I would like to export a mongodb collection using mongodump after performing a series of inserts. Something like this:

// requires and initializing stuff left out for brevity
db.open(function(err, db) {
    if(!err) {
        db.collection('test', function(err, collection) {
            var docs = [{'hello':'doc1'}, {'hello':'doc2'}, {'hello':'doc3'}];

            collection.insert(docs, {safe:true}, function(err, result) {

                // Execute mongodump in this callback???

            });
        });
    }
});

2 Answers 2

24

Try using child_process.spawn(command, args):

var spawn = require('child_process').spawn;

// ...
  collection.insert(docs, {safe:true}, function(err, result) {
    var args = ['--db', 'mydb', '--collection', 'test']
      , mongodump = spawn('/usr/local/bin/mongodump', args);
    mongodump.stdout.on('data', function (data) {
      console.log('stdout: ' + data);
    });
    mongodump.stderr.on('data', function (data) {
      console.log('stderr: ' + data);
    });
    mongodump.on('exit', function (code) {
      console.log('mongodump exited with code ' + code);
    });
  });
// ...
Sign up to request clarification or add additional context in comments.

2 Comments

this was useful to me.I would like to add one more info."/usr/local/bin/mongodump" need to the the bin folder path of your mongodb,only then it works
I want to run this on cloud servers like Heroku. How do i install the mongodump or is there any similar library that performs the same option?
1

A different year, a different answer.

You can use something like Shelljs to exec mongodump or any other commands that the UNIX shell provides.

1 Comment

I want to run this on cloud servers like Heroku. How do i install the mongodump or is there any similar library that performs the same option?

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.