Import Documents into MongoDB from an Array of JSON Documents

When using mongoimport, you can use the --jsonArray parameter to import an array of JSON documents.

Example

Suppose we have the following JSON document called pets_array.json:

[
    {"_id":1.0,"name":"Wag","type":"Dog"},
    {"_id":2.0,"name":"Bark","type":"Dog"},
    {"_id":3.0,"name":"Meow","type":"Cat"}
]

If we try to import that into MongoDB without using the --jsonArray parameter, we get the following error:

2021-01-03T13:52:58.360+1000	no collection specified
2021-01-03T13:52:58.360+1000	using filename 'pets_array' as collection
2021-01-03T13:52:58.366+1000	connected to: mongodb://localhost/
2021-01-03T13:52:58.371+1000	Failed: cannot decode array into a D
2021-01-03T13:52:58.371+1000	0 document(s) imported successfully. 0 document(s) failed to import.

Basically, it can’t decode the array into a document.

To fix this, we can simply add the --jsonArray parameter:

mongoimport --db=PetHotel --jsonArray --file=pets_array.json

Output:

2021-01-03T13:58:13.407+1000	no collection specified
2021-01-03T13:58:13.408+1000	using filename 'pets_array' as collection
2021-01-03T13:58:13.421+1000	connected to: mongodb://localhost/
2021-01-03T13:58:13.450+1000	3 document(s) imported successfully. 0 document(s) failed to import.

This tells us that all three documents were imported successfully.

We can now take a look at the collection to check:

db.pets_array.find()

Result:

{ "_id" : 1, "name" : "Wag", "type" : "Dog" }
{ "_id" : 3, "name" : "Meow", "type" : "Cat" }
{ "_id" : 2, "name" : "Bark", "type" : "Dog" }

As expected, all three documents are in the newly created collection.

The collection is newly created because we didn’t specify a collection to import the documents into. If we had, then they would have been imported into the specified collection.

Don’t Have mongoimport?

mongoimport is part of the MongoDB Database Tools package. The MongoDB Database Tools are a suite of command-line utilities for working with MongoDB.

If you’re not sure whether you have the MongoDB Database Tools/mongoimport installed, try running the following command in your Terminal or Command Prompt to check:

mongoimport --version

If you have it, you should see version information, etc. If you don’t have it, you can use the installation instructions over at the MongoDB website to install it on to your system.

Where to Run mongoimport Commands?

You need to run mongoimport commands from your system’s command line (e.g. a new Terminal or Command Prompt window).

Don’t run them from the mongo shell.