To import a JSON file containing a collection of documents into MongoDB, you can use the mongoimport command-line tool provided by MongoDB. Here’s how you can do it:
- Prepare your JSON file: Ensure your JSON file contains a valid JSON array of objects, where each object represents a document to be inserted into the collection.
- Use mongoimport: Open your terminal or command prompt and navigate to the directory where your JSON file is located.
- Run the
mongoimport
command:
mongoimport --db your_database_name --collection your_collection_name --file your_json_file.json
Replace `your_database_name` with the name of your MongoDB database and
`your_collection_name` with the name of the collection where you want to insert the documents. Also, replace your_json_file.json with the name of your JSON file.
Additionally, you may need to specify other options depending on your specific requirements. Some common options include:
- –jsonArray: Specify this option if your JSON file contains a JSON array.
- –host: Specify the MongoDB host.
- –port: Specify the MongoDB port.
- –username: Specify the username for authentication.
- –password: Specify the password for authentication.
- –authenticationDatabase: Specify the authentication database.
- –drop: Specify this option if you want to drop the collection before importing the data.
Here’s an example command with additional options:
mongoimport --db your_database_name --collection your_collection_name --file your_json_file.json --jsonArray --host localhost --port 27017 --username your_username --password your_password --authenticationDatabase admin --drop
Adjust the options according to your MongoDB setup and requirements. After running the mongoimport command, MongoDB will insert the documents from the JSON file into the specified collection in the specified database.