Technology Encyclopedia Home >How to import data from local to MongoDB using mongorestore (entire database) or mongoimport (single collection)?

How to import data from local to MongoDB using mongorestore (entire database) or mongoimport (single collection)?

To import data from local to MongoDB, you can use mongorestore for an entire database or mongoimport for a single collection.

1. Using mongorestore (Entire Database)

mongorestore is used to restore a MongoDB database from a binary backup (dump folder).

Steps:

  • Ensure you have a dump folder containing the database backup (usually created by mongodump).
  • Run mongorestore with the path to the dump folder.

Example:

mongorestore /path/to/dump/

This restores all databases in the dump folder. To restore a specific database:

mongorestore --db=mydatabase /path/to/dump/mydatabase/

Note: If MongoDB requires authentication, add --username, --password, and --authenticationDatabase flags.

Tencent Cloud Recommendation:
For managed MongoDB on Tencent Cloud, ensure the instance is accessible (check network/security groups) and use the MongoDB Console or CLI for backups/restores.


2. Using mongoimport (Single Collection)

mongoimport imports data from a JSON, CSV, or TSV file into a specific collection.

Steps:

  • Prepare your data file (e.g., data.json).
  • Run mongoimport with the file path and target collection.

Example (JSON file):

mongoimport --db=mydatabase --collection=mycollection --file=data.json

For CSV:

mongoimport --db=mydatabase --collection=mycollection --type=csv --headerline --file=data.csv

Flags:

  • --username, --password: For authentication.
  • --drop: Drop the collection before import.

Tencent Cloud Recommendation:
For large datasets, use Tencent Cloud MongoDB Data Import Tool or batch imports to avoid performance issues.

Note: Ensure the MongoDB instance allows external connections (check whitelist/IP access control in Tencent Cloud Console).