CSV (Comma-Separated Values) files store tabular data in plain text format, making them widely used for data exchange. If you want to import CSV data into MongoDB, follow the steps below.
Ensure your CSV file is properly formatted with column headers. Example:
name,age,city John,25,New York Alice,30,Los Angeles Bob,28,Chicago
Ensure MongoDB is running. If not, start the MongoDB server using the following command:
mongod
Use the mongoimport
tool to import the CSV file into MongoDB. Run the following command:
mongoimport --db mydatabase --collection mycollection --type csv --headerline --file data.csv
Explanation:
Open the MongoDB shell and check if the data was imported successfully:
mongo use mydatabase db.mycollection.find().pretty()
By following these steps, you can efficiently import CSV data into MongoDB. This method is useful for data migration, analytics, and database management.