System: OS: OS X 10.9
Mongo: MongoDB shell version 2.4.9
Link: Mongo import and Mongo Export
Mongo import or export used for flexible manipulating with collections full databases or some parts of collections. With this instruments manipulating with data can be realised easily.
What specially you can do with that tools?
For exporting you need specify db name, collection and output file where result of exporting will be stored.
1 |
mongoexport --db project_test_db --collection users --out export/users.json |
As a result you will get new folder export with JSON files.
Full example of mongoexport with all main parameters for exporting from server looks like this:
1 |
mongoexport --host hostname.com --port 37017 --username user --password pass --db project_test_db --collection users --out export/users.json |
However main power of mongoexport in using query for exporting. Imagine that you have collection with 100 000 000 records and you need only some part for testing or only some particular record or only record for one month:
1 |
mongoexport --db project_test_db --collection users --out export/users.json --query '{"userMail" : "user@mail.com"}' |
With this command you will get records that match with query only records where “userMail” field equals “user@mail.com”
Also one example of exporting with parameters SORT, LIMIT and SKIP:
1 |
mongoexport --db project_test_db --collection users --sort '{fieldName: 1}' --limit 100 --skip 10 --out export/users.json |
Translation of this command looks like that: export from project_test_db database from users collection to export/users.json file also before exporting sort records in collection by fieldName field skip first 10 records and return maximum 100 records.
When you already have exported JSON file with data what you need you can use mongoimport for inserting data to db.
1 |
mongoimport --db project_test_db --collection users --file export/users.json |
In general mongoimport quite similar to mongoexport main difference in file parameter which specifies source JSON file for importing data.
1 |
mongoimport --host hostname.com --port 27017 --username user --password pass --collection users --db project_test_db --file /export/users.json |