Summary: in this tutorial, you’ll learn how to use the mongoimport tool to import a JSON file into a local MongoDB database server.
Download & install the mongoimport tool
To import JSON files into the MongoDB server, you use the mongoimport tool. Starting from MongoDB 4.4, the mongoimport tool is released separately from the MongoDB server. Therefore, you need to download and install it:
- First, download the mongoimport tool on this page.
- Second, follow this instruction to install the mongoimport tool.
Download the JSON sample file
The following books.json file contains 431 documents about books.
Before importing it into your local MongoDB database server, you need to click the following download button:
Download books.zip FileNote that the downloaded file is in the zip format, you need to extract it to books.json file.
Import the books.json to a MongoDB database server
First, open the Terminal on macOS and Linux or Command Prompt on Windows.
Second, navigate to the database tools directory where the mongoimport tool is located. On Windows, it’s C:\Program Files\MongoDB\Tools\100\bin where 100 is the version of the tool.
Third, use the following command to import the books.json file into the MongoDB database server:
Code language: Shell Session (shell)mongoimport c:\data\books.json -d bookdb -c books --drop
In this command:
- First, start with the
mongoimportprogram name. - Next, specify the path to the
books.jsondata file. In this example, it isc:\data\books.json. - Then, use
-d bookdbto specify the target database, which isbookdbin this example. - After that, use
-c booksto specify the target collection, which isbooksin this case. - Finally, use the
--dropflag to drop the collection if it exists before importing the data.
If the import was successful, you will see the following output:
Code language: Shell Session (shell)2022-02-22T14:30:10.869+0700 connected to: mongodb://localhost/ 2022-02-22T14:30:10.872+0700 dropping: bookdb.books 2022-02-22T14:30:10.926+0700 431 document(s) imported successfully. 0 document(s) failed to import.
Fourth, type the following command from the terminal to connect to the bookdb database on the local database using mongo shell:
Code language: Shell Session (shell)mongosh bookdb
Fourth, use the countDocuments() method to return the number of documents in the books collection:
Code language: Shell Session (shell)db.books.countDocuments()
It returned 431 documents.
Finally, use the find() method to return the document with the_id 1 to examine the document:
Code language: Shell Session (shell)db.books.find({"_id":1})
In this tutorial, you’ve learned how to use the mongoimport tool to import books.json into the local MongoDB database server.