MongoDB Tutorial 18 : MongoDB import/export data

Load data from the mongo shell

If you are in the mongoshell and want to import some data, then the simplest approach is to use the load(path) function in the mongoshell, that will load data from a JSON file:
load("/full/path/to/sample-data.json")

Mongo Import – import JSON data

Note that mongoimport and mongoexport use data in JSON format, whereas MongoDB stores them in BSON, which is superset of JSON. Thus mongoimport and mongoexport don’t reliably preserve all BSON data types, therefore should not be used for production backups, but they are ok for testing and playing with MongoDB.

Import data into selected database and collection

mongoimport --db mydb --collection mycoll --file mydata.json
If you omit collection parameter, then target collection name will be taken from the filename (without file extension):
# Imports into "customers" collection:
mongoimport --db mydb --file customers.json

Import using shorter syntax:

mongoimport -d mydb -c mycoll < mydata.json

Mongo Export – export JSON/CSV data

mongoexport has mostly the same parameters as mongoimport.

Export selected collection as JSON

mongoexport --db mycoll --collection mycoll --out mydata.json

Export selected collection as CSV

mongoexport --db mycoll --collection mycoll --out mydata.csv --type=csv

Export only documents matching query:

mongoexport --db sales --collection contacts --query '{"city": "Cracow"}'

Export data from remote MongoDB host

mongoexport --host mongodb1.mycorp.kam --port 37017 --username user
            --password pass --collection contacts --out mdb1-examplenet.json

Comments

Popular posts from this blog

Hive Tutorial 31 : Analytic Functions

Hive Tutorial 37 : Performance Tuning