Introduction
In this lab, you will learn the essential skills for importing data into a MongoDB database. You will work with two common data formats: JSON and CSV. You will use the mongoimport command-line tool to load data from files into MongoDB collections. The lab will guide you through importing data, specifying data types during import, and verifying that the data has been loaded correctly using queries and the mongoexport tool.
Import Data from a JSON File
In this first step, you will import data from a JSON file into a MongoDB collection. JSON (JavaScript Object Notation) is a native format for MongoDB, which makes the import process straightforward. We will use the mongoimport utility, a command-line tool designed for this purpose.
A sample file named books.json has been created for you in the ~/project directory. First, inspect its contents from your terminal.
cat ~/project/books.json
You should see the following output, which is an array of JSON documents:
[
{
"_id": 1,
"title": "MongoDB Basics",
"author": "Jane Smith",
"year": 2023,
"tags": ["mongodb", "database", "nosql"]
},
{
"_id": 2,
"title": "Python Programming",
"author": "John Doe",
"year": 2022,
"tags": ["python", "programming"]
},
{
"_id": 3,
"title": "Data Science Handbook",
"author": "Alice Johnson",
"year": 2021,
"tags": ["data science", "python", "machine learning"]
}
]
Now, import this data into a new database called library_db and a collection named books.
mongoimport --db library_db --collection books --file ~/project/books.json --jsonArray
Let's break down the command options:
--db library_db: Specifies the target database.--collection books: Specifies the target collection within the database.--file ~/project/books.json: Provides the path to the input file.--jsonArray: Informsmongoimportthat the file contains a single JSON array, where each element is a document to be inserted.
You will see output indicating the progress and completion of the import:
2025-08-27T15:10:40.411+0800 connected to: mongodb://localhost/
2025-08-27T15:10:40.417+0800 3 document(s) imported successfully. 0 document(s) failed to import.
To verify that the data was imported correctly, you will now connect to MongoDB using the MongoDB Shell, mongosh.
mongosh
Once inside the shell, switch to the library_db database:
use library_db
Now, count the documents in the books collection to confirm that all three records were imported.
db.books.countDocuments()
The output should be 3. You can also view one of the imported documents to check its structure.
db.books.findOne()
This will display the first document from the collection. Finally, exit the MongoDB Shell to return to your terminal.
exit
Import Data from a CSV File
Next, you will import data from a CSV (Comma-Separated Values) file. CSV is a common format for tabular data, and mongoimport can easily convert it into MongoDB documents.
A sample CSV file named library_members.csv has been prepared for you. Take a look at its contents.
cat ~/project/library_members.csv
The file contains a header row and three data rows:
name,age,membership_status
John Doe,35,active
Jane Smith,28,active
Mike Johnson,42,expired
Now, use mongoimport to load this data into a new collection called members in the same library_db database.
mongoimport --db library_db --collection members --type csv --file ~/project/library_members.csv --headerline
Here are the new options used for CSV import:
--type csv: Specifies that the input file format is CSV.--headerline: Tellsmongoimportto use the first line of the file as the field names for the documents.
The output will confirm the successful import:
2025-08-27T15:11:33.553+0800 connected to: mongodb://localhost/
2025-08-27T15:11:33.558+0800 3 document(s) imported successfully. 0 document(s) failed to import.
Let's verify the import. Connect to the MongoDB Shell and check the members collection. You can specify the database directly when launching mongosh to save a step.
mongosh library_db
Now, count the documents in the members collection.
db.members.countDocuments()
The result should be 3. Next, inspect one of the documents to see how mongoimport converted the CSV row into a BSON document.
db.members.findOne()
You will see a document similar to this. Notice that all values, including the age, are imported as strings by default.
{
_id: ObjectId("..."),
name: 'John Doe',
age: '35',
membership_status: 'active'
}
You will learn how to handle data types in the next step. For now, exit the shell.
exit
Handling Data Types During CSV Import
When importing from a CSV file, mongoimport treats all values as strings by default. This can be an issue if you need to perform numerical or date-based operations. In this step, you will learn how to import CSV data and then convert data types in MongoDB.
Let's re-import the library_members.csv data into a new collection called typed_members, and then convert the age field to an integer.
First, create a CSV file without headers since we'll define field names explicitly:
tail -n +2 ~/project/library_members.csv > ~/project/library_members_no_header.csv
Now import the data with explicit field names:
mongoimport --db library_db --collection typed_members --type csv --file ~/project/library_members_no_header.csv --fields "name,age,membership_status"
After importing, we need to convert the age field from string to integer using MongoDB's update operation:
mongosh library_db --eval "db.typed_members.updateMany({}, [{ \$set: { age: { \$toInt: \"\$age\" } } }])"
This command uses MongoDB's aggregation pipeline within an update operation to convert all age values from strings to integers using the $toInt operator.
Now let's verify the result by connecting to mongosh and inspecting the data types in the typed_members collection.
mongosh library_db
First, find one document in the collection to see the converted data:
db.typed_members.findOne()
The output should show the age field as a number:
{
_id: ObjectId("..."),
name: 'Jane Smith',
age: 28,
membership_status: 'active'
}
You can explicitly check the type of the age field using JavaScript's typeof operator within mongosh:
typeof db.typed_members.findOne().age
The output should be number, confirming that the data type conversion was successful. This allows you to perform numerical queries, such as finding all members older than 30:
db.typed_members.find({ age: { $gt: 30 } })
This query will now work as expected and return two documents. Exit the shell to proceed to the next step:
exit
Verifying Data with Queries and Exports
The final step in any data import process is thorough verification. This involves not only checking document counts but also running queries to sample the data and ensure its integrity. You can also export the data to an external file for further analysis.
First, connect to your database with mongosh.
mongosh library_db
You can list all collections in the database to see the results of your work so far.
show collections
You should see books, members, and typed_members. Now, let's run some queries to validate the data. For the books collection, find all books that have the "python" tag.
db.books.find({ tags: "python" })
This query demonstrates searching within an array field. You should see two books returned. For the typed_members collection, find all members with an "active" membership status.
db.typed_members.find({ membership_status: "active" })
This should return two members. These simple queries help confirm that the data is structured as expected.
Another powerful verification tool is mongoexport, which does the reverse of mongoimport. It exports a collection to a file. Let's export the books collection to a new JSON file. Exit the shell first.
exit
Now, run the mongoexport command from your terminal.
mongoexport --db library_db --collection books --out ~/project/exported_books.json
The --out flag specifies the path for the output file. This command will create a file named exported_books.json in your project directory. You can view its contents to verify the export.
cat ~/project/exported_books.json
Each line in the output file is a self-contained JSON document from your collection. This file can be used for backups, migration, or analysis with other tools.
Summary
In this lab, you have learned how to import data into MongoDB from both JSON and CSV files using the mongoimport utility. You practiced importing a JSON array into a collection and verified the result using mongosh. You then imported data from a CSV file, first with default string types, and then by specifying data types for fields like numbers. Finally, you learned how to verify the integrity of your imported data by running queries in mongosh and by exporting a collection back to a file using mongoexport. These are fundamental skills for managing data in any MongoDB project.

