How to Use the mongoimport to Import a JSON file into the local MongoDB server

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 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 File

Note that the downloaded file is in the zip format, you need to extract it to books.json file.

Import the books.json to MongoDB database sever

MongoDB installation comes with a very useful tool for importing data called mongoimport located in the bin directory.

First, open the Terminal on macOS and Linux or Command Prompt on Windows.

Second, use the following command to import the books.json to the MongoDB database server:

mongoimport c:\data\books.json -d bookdb -c books --drop
Code language: Shell Session (shell)

In this command:

  • First, start with the mongoimport program name.
  • Next, specify the path to the books.json data file. In this example, it is c:\data\books.json.
  • Third, use -d bookdb to specify the target database, which is bookdb in this example.
  • Fourth, use -c books to specify the target collection, which is books in this case.
  • Finally, use the --drop flag to drop the collection if it exists before importing the data.

If the import was successful, you will see the following output:

connected to: mongodb://localhost/ dropping: bookdb.books 431 document(s) imported successfully. 0 document(s) failed to import.
Code language: Shell Session (shell)

Third, type the following command from the terminal to connect to the bookdb database on the local database using mongo shell:

mongo bookdb
Code language: Shell Session (shell)

Fourth, use the count() method to return the number of documents in the books collection:

Code language: Shell Session (shell)

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)

In this tutorial, you’ve learned how to use the mongoimport tool to import books.json into the local MongoDB database server.

Was this tutorial helpful ?