MongoDB: Create database and import multiple

Leipzig, Germany

MongoDB: Create database and import multiple collections

Create new database

Start mongodb shell, create a new database by using the use command. Check the currently selected database and list all collections.

> use db_newone 
switched to db db_newone
> db
db_newone
> db.getCollectionNames()
[ ]

Shell script to import multiple collections at once

Assuming your shell script lives under ~/project/bin/import.sh and the exported collections under ~/project/data/<collectionname>.json.
For example data/collection_one.json and data/collection_two.json.

Now you can use the following script to import the collections:

import.sh

#! /bin/bash

db=db_newone;
scriptpath="$( cd "$(dirname "$0")" ; pwd -P )";
cd $scriptpath/../data/;

for c in $(ls *.json); do
  echo "> start importing collection >${c%.*}<";
  mongoimport --db $db --collection ${c%.*} $c;
done

Execute it!

bin/import.sh

> start importing collection >collection_one<
2017-01-01T00:00:00.000+0000    connected to: localhost
2017-01-01T00:00:00.001+0000    imported 43 documents
> start importing collection >collection_two<
2017-01-01T00:00:00.000+0000    connected to: localhost
2017-01-01T00:00:00.001+0000    imported 89 documents

Check that everything went well

> db.getCollectionNames()
[
        "collection_one",
        "collection_two"
]

Done :)