Search code examples
node.jsmongodbcsvremote-server

I need to call mongoexport remotely and get the result from node.js


I'm not sure how to go about this, I need to export a mongodb collection as an .csv. Calling mongoexport with spawn.child_process in node will accomplish this but my mongodb server and node server are currently on separate machines.

How can I remotely call mongoexport on my mongo server from my node server and then get the .csv to the node server?


Solution

  • First, make sure the MongoDB port is opened and you can connect from the server. Then, use

    mongoexport --username user --password pass --host host --db database --collection coll --type=csv --fields=displayName,emailAddress --query='{"status": "verified"}' -o users-YEAR-DAY-MONTH.csv
    

    If the server it's in a public network make sure to use authentication.

    https://docs.mongodb.com/manual/security/

    Alternatively, it might be simpler to run an ssh command, run mongoexport on the MongoDb server and then sftp back the file (maybe zip it first).

    More info on mongoexport