MongoDB: Create Database and User – Mongo Shell

In MongoDB, in the opposite to traditional SQL databases, there is no need, as well as possibility, to create an empty database.

To create a new database in MongoDB, it needs to insert at least one document into it.

In this article i will show how to create a new database and a user for this database in MongoDB from the command line, using mongo shell.

I will also show how to list collections, get all documents and delete a MongoBD database.

Cool Tip: How to connect to remote MongoDB server from the command line using mongo shell! Read More →

Create Database in MongoDB

MongoDB-Lend: A database holds a set of collections. A collection holds a set of documents. Document is a set of fields (key-value pairs).

To create a new_database in MongoDB, firstly it needs to select this database to use:

> use new_database

To check the currently selected database, run:

> db

However, if you list all databases in MangoDB you won’t find a new_database there:

> show dbs
local        0.000GB
test         0.000GB

Create MongoDB Database: A new database in MongoDB won’t be created until you insert at lest one document into it.

Create a new_collection and insert a document with some_key and some_value pair:

> db.new_collection.insert({ some_key: "some_value" })

The new_database has been created as only the first document was inserted:

> show dbs
local        0.000GB
new_database 0.000GB
test         0.000GB

Create user for MongoDB database

To create a new_user for new_database with readWrite permissions in MongoDB, run:

> db.createUser(
    user: "new_user",
    pwd: "some_password",
    roles: [ { role: "readWrite", db: "new_database" } ]

Cool Tip: How to enable auth in MongoDB and create admin/root users! Read More →

To list all collections in the selected MangoDB database, run:

> show collections

To get all documents from new_collection, run:

> db.new_collection.find()
{ "_id" : ObjectId("5bd189d710b0277d46cf8ff5"), "some_key" : "some_value" }

Delete MongoBD database

To delete selected MongoBD database, run:

>  db.dropDatabase()
{ "dropped" : "new_database", "ok" : 1 }

3 Replies to “MongoDB: Create Database and User – Mongo Shell”

  1. Nice blog for a beginner . must appreciate and well desribed to the point

  2. Thanks for the tutorial. Really helpful.

Leave a Reply