I am looking for a way to create a new database and a collection using only the terminal, without using Mongo shell or Mongo Compass GUI.
The idea is to create the db and collection from the terminal before using mongoimport
, like:
# Create database `company-example` and collection `employees` from the terminal
# ...
# ...
# Import the data to the collection
mongoimport --db=company-example --collection=employees --file=employees.json --jsonArray
I could create a npm package and run it with with Node from the terminal, but I am wondering if there is a simpler way?
You can "clone" a database and an empty collection from a predefined database and collection (for the purpose of creating a new database with an empty collection). This is based upon another post by the author: clone collection in mongoDB in the same db.
First, create a database called as a dummyDB
, and an empty collection called testColl
. This is used to create/clone a database with one collection that is empty.
This command from terminal will create a clone:
mongodump --archive --db=dummyDB --collection=testColl | mongorestore --archive --nsFrom="dummyDB.*" --nsTo="examples.*"
The cloned database is examples
and the collection with no documents testColl
.
This process is useful in case you are creating the clones again and again.