My Brain on Code

Importing JSON Into MongoDB

Lets say you have a bunch of data in a JSON file to import into your MongoDB database. Luckily, you can use the mongoimport command to do this. However, there are a few things you need to know:

  • MongoImport expects only one document per line.
  • You will be importing into an actual collection in the database.

Creating a Collection Automatically

If you don’t already have an existing collection, you can use the --collection argument to create one during the import.

JSON data

A sample JSON file you can use to test imports can be found below. It is simply a list of people

{"FirstName": "Bruce", "LastName": "Wayne", 
    "Email": "bwayne@Wayneenterprises.com"}
{"FirstName": "Lucius", "LastName": "Fox", 
    "Email": "lfox@Wayneenterprises.com"}
{"FirstName": "Dick", "LastName": "Grayson", 
    "Email": "dgrayson@Wayneenterprises.com"}

Importing the Data

Now it’s time to actually import our data:

mongoimport --host localhost --db testdb \
    --collection persons --username user \
    --password pass --type json \
    --file persons.json

--type: The type of file we are importing. This could be csv, json, or tsv --file: The file we are importing

That’s all there is to it!