Skip to main content

Mongoimport

mongoimport is a command-line utility that comes with MongoDB and is used for importing content from a JSON, CSV, or TSV file into a MongoDB database. It's particularly useful for initial data loading or for transferring data between different MongoDB instances.

Basic Syntax

The basic syntax of mongoimport is as follows:

mongoimport --db <database_name> --collection <collection_name> --file <input_file>

Key Options

Here are some of the key options you can use with mongoimport:

  • --db <database_name>: Specifies the database into which to import the data.

  • --collection <collection_name>: Specifies the collection into which to import the data.

  • --file <input_file>: Specifies the location and name of the file from which to read data.

  • --type <file_type>: Specifies the file type to import. The default is json. Other options include csv and tsv.

  • --headerline: Indicates that the first line in a CSV or TSV file is a header line. mongoimport will use this line as the field names for imported data.

  • --fields <field1,field2,...>: Specifies the fields for a CSV or TSV import. Use this if the file doesn't have a header line.

  • --jsonArray: Indicates that the input file contains a single JSON array of documents.

  • --drop: Drops the collection before importing the data. Be cautious when using this option as it will remove all existing data in the collection.

  • --upsert: Updates existing objects that match a document in the import file, inserting any that don't match.

  • --upsertFields <field1,field2,...>: Specifies which fields should be used for the upsert operation.

  • --numInsertionWorkers <number>: Specifies the number of workers for inserting documents. Useful for parallelizing imports.

  • --ssl: Connects to MongoDB over SSL.

  • --authenticationDatabase <name>: Specifies the database that holds the user's credentials.

  • --username <name> and --password <password>: Specifies the username and password for authentication.

Examples

  1. Importing a JSON file into a specific database and collection

    mongoimport --db testDB --collection testCollection --file data.json
  2. Importing a CSV file with a header line

    mongoimport --db testDB --collection testCollection --type csv --headerline --file data.csv
  3. Importing a CSV file without a header line and specifying fields

    mongoimport --db testDB --collection testCollection --type csv --fields name,age,email --file data.csv
  4. Importing data with upserts

    mongoimport --db testDB --collection testCollection --upsert --file data.json

Considerations

  • mongoimport is a single-threaded tool, so importing large amounts of data may take some time.

  • It's not suitable for complex data transformations or validations; it's designed for simple imports.

  • Be cautious with the --drop option, especially in production environments, as it will remove all existing data in the collection.