The Compleat Hangler

Dumping JSON-formatted data from Mongo into a flat file

For a class project, I’ve downloaded and stored a large amount of JSON data in MongoDB. Now I’d like to export those JSON objects to a flat file from the command line. For anyone else who might be interested (and for my own future reference!), the command is:

mongo localhost/yourdbname --eval "db.yourcollectionname.find(
  {'your': 'filter'}).forEach(function(x){
  })" >> filename

(You might need to remove the line breaks in the above command.)

A few caveats before you work with the output:

  • There will be a couple of lines of Mongo connection information at the top, which you should delete.
  • The JSON objects will not be comma separated; one will be printed per line, though, which makes them easy to load into other tools.
  • If you are using Mongo’s default keys, you will have a key-value pair of “_id” : ObjectID(“12345”). This value is not valid JSON and will need to be cleaned.