9

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?

Josh Elias
  • 3,250
  • 7
  • 42
  • 73

4 Answers4

20

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

Gianfranco P.
  • 10,049
  • 6
  • 51
  • 68
  • Thats definately right way to go. I'm getting an "authentication failed" error when I try logging in. My user doesn't have a password so I left that field blank in mongoexport. I do use a private key to ssh into these servers, would that need to come into play here? – Josh Elias Oct 24 '12 at 13:39
  • you can specify the sshkey on `ssh -i identity_file` but that's another topic – Gianfranco P. Oct 24 '12 at 13:42
  • it seems to run without setting the username or pass – Josh Elias Oct 24 '12 at 13:46
3

I used @GianfrancoP's answer but the syntax is deprecated. You'll now need to include the fieldnames you want to export. Here's updated syntax:

mongoexport --username user --password pass --host host --db database --collection coll --type=csv --fields fieldname
toddg
  • 2,863
  • 2
  • 18
  • 33
0

The answer given by GianPaJ is the solution I'm using, however a shortcoming is that it is only outputting the exported data to the remote host, not to your client.

One work around is to use SCP or SFTP on the exported file. I will update this post if I figure out how to actually transfer that file with a mongoexport option.

Jason
  • 259
  • 3
  • 14
  • `mongoexport --host {host} -f {fields} -d {db} - c {coll} --csv -o {absolute_local_path}` saves file specified in absolute path locally for me. – David Barker Jun 17 '13 at 11:19
0

I have created this command to skip the stfp step to export my database.

ssh user@remote_host_ip  "mongoexport --host localhost --db dbname --username username --password pass --authenticationDatabase admin --collection collectionname --fields field1,field2 --type=csv" >> export.csv

you can ssh to remote and provide mongodb username,password and authentication db if you have applied authentication on mongodb other wise skip it. This will create the export.csv on the local system.

Malik Faiq
  • 433
  • 6
  • 18