Mongoexport and Mongoimport with Examples: Easy Guide

This image has an empty alt attribute; its file name is image-12.png

Today in this article, we will learn about Mongoexport and Mongoimport. Let’s go through this in detail. When we can use mongoexport and mongoimport with examples, we will explain :

Mongoexport :

• Mongoexport exports the data in json format
• Useful for moving the data to other databases
• mongoexport must run on a single specified database and collection.
• You cannot run mongoexport on an entire database, for that you need to use mongodump

Examples :

MongoExport in JSON format :

Syntax :
mongoexport -d <db_name> -c <collection_name> -o <collection_name>.json
Example :
mongoexport -d sample -c test -o test.json
Mongoexport and Mongoimport

MongoExport in csv format :

Syntax :
mongoexport -db <db_name> -collection <collection_name> --type CSV --fields=<field_name> --out <collection_name>.csv
Example :
mongoexport --db=sample --collection=test --type=csv --fields=EmpNo,Place --out=test.csv
Mongoexport and Mongoimport with Examples: Easy Guide

If you want without the headerline option, use –noHeaderLine option

Syntax :
mongoexport --db=<db_name> --collection=<collection_name> --type=csv --fields=field_name --out=<collction_name>.csv --noHeaderLine
Example :
mongoexport --db=sample --collection=test --type=csv --fields=EmpNo,Place --out=test1.csv --noHeaderLine
Mongoexport and Mongoimport with Examples: Easy Guide

MongoImport :

  • Used to import the data into mongodb
  • This is to take an output of mongoexport as input
  • MongoImport supports JSON, CSV and TSV formats
  • mongoimport also import a collection, it can’t be done on the whole database. Here is its drawback
Syntax :
mongoimport -d <target_db_name> -c <target_collection_name> --file=<json_file_name>
Example :
mongoimport -d sample_new -c test --file=test.json
Mongoexport and Mongoimport with Examples: Easy Guide

Other arguments can be used in mongoimport :

  • –drop : we can use the –drop option also to drop the collection before the import takes place.
  • –stopOnError: If this option is specified, the import will stop on the first error if it encounters
  • –type: This can be either JSON, CSV, or TSV to specify what type of file will be imported, the default type of the file is JSON

So, here are the simple steps with examples how you can use mongoexport and mongoimport. Hope this helps!!

Also, you can get more information from the MongoDB Doc itself.

Reference Articles related to Mongo:

Leave a Reply