MongoDB – Converting DB data to JSON using mongodump and bsondump

MongoDB

This worked better than I expected.  Converting the DB data to JSON is a one-way action. Well, at least I do not know of a way to convert it back.  I did not want to install mongo-tools on the server.  So after creating the dump I zipped the files up and downloaded the dump to my local, converting it there.

Install bsondump

bsondump documentation: https://www.mongodb.com/docs/database-tools/bsondump/

This is for MacOS.

  1. Install Apple’s Command Line Developer Tools:
    xcode-select --install
  2. Install MacPorts (download the appropriate version from here The MacPorts Project — Download & Installation )
  3. Install mongo-tools with – Install mongo-tools on macOS with MacPorts
    sudo port install mongo-tools

Get DB dump

mongodump documentation: https://www.mongodb.com/docs/database-tools/mongodump/

I’m 90% sure that mongodump is a utility that comes with MongoDB.  I do not think you need to install it.

  1. Gain access to the mongo server
  2. Run mongodump to dump the DB
    mongodump -u <username> -h 127.0.0.1 --db <database> --out /tmp/data --authenticationDatabase <database> -p "" --verbose

    • This is run at the normal shell prompt, do not enter the mongo shell.
  3. Enter password at prompt
  4. Compress the dump into one zip file
    tar -czvf <dumpfilename> data
  5. Download
  6. Extract
    tar -xzvf <dumpfilename>

Convert dump to json

  1. View the file and pipe it into bsondump to convert
    cat <db.bson-file> | bsondump --pretty > <new-text-file-name>

Leave a Reply

Your email address will not be published. Required fields are marked *