Uros C
Uros C

Reputation: 2017

Create a MongoDB database and a collection from terminal (without shell)

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?

Upvotes: 1

Views: 1103

Answers (2)

prasad_
prasad_

Reputation: 14317

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.

Upvotes: 1

Boris Kukec
Boris Kukec

Reputation: 721

I assume that for some reason you would like to have DB and collection created prior to import.

  1. create a script for example employees.js, with content:

db.createCollection("employees", {collation:{locale:"en", strength:2}});

  1. start command from the terminal:

    mongo company-example employees.js

Please notice the first parameter of mongo command is DB name and the second is your script. If DB does not exist it will be created automatically.

Upvotes: 1

Related Questions