Importing Data into MongoDB - JSON and CSV

Learn how to import data into a MongoDB database from JSON and CSV files using various methods and tools.


Prerequisites

Before you begin, make sure you have the following prerequisites:

  • MongoDB installed and running locally or accessible through a connection string.
  • JSON and CSV data files that you want to import.

Using the mongoimport Command

The `mongoimport` command is a MongoDB utility for importing data from JSON and CSV files. Here's how you can use it:

# Import JSON data
mongoimport --db your_database --collection your_collection --file data.json
# Import CSV data
mongoimport --type csv --db your_database --collection your_collection --headerline --file data.csv

Using MongoDB Compass

MongoDB Compass is a graphical user interface for MongoDB. You can use it to import data with a few clicks:

  1. Open MongoDB Compass and connect to your MongoDB server.
  2. Select your target database and collection.
  3. Click the "Add Data" button and choose your JSON or CSV file to import.

Using a Programming Language (e.g., Node.js)

You can write a script in a programming language like Node.js to read JSON or CSV files and insert data into MongoDB using the MongoDB driver for that language. Here's an example using Node.js:

const fs = require('fs');
const { MongoClient } = require('mongodb');
const data = JSON.parse(fs.readFileSync('data.json', 'utf8'));
async function importData() {
const client = new MongoClient('mongodb://localhost:27017', { useUnifiedTopology: true });
try {
await client.connect();
const db = client.db('your_database');
const collection = db.collection('your_collection');
await collection.insertMany(data);
} finally {
client.close();
}
}
importData();

Conclusion

You've learned how to import data into MongoDB from JSON and CSV files using different methods, including the `mongoimport` command, MongoDB Compass, and a programming language like Node.js. These techniques provide flexibility for importing data into your MongoDB databases.