Learn commands to create and drop a MongoDB database.
Create a database
The below command is used to create or access a MongoDB database.
use <database-name>;
Replace <database-name> with the name you want to keep to your database.
The above use command does not create anything until you insert the first record. Here is an example of an insert command. In this example, we are inserting a task into
the tasks collection.
db.tasks.insertOne({
name: "Learn Chapter 1",
});
The below command verifies the database creation. It returns names and sizes of all the
databases.
show databases;
You will see some databases other than todo. They are created by default by MongoDB on installation and are used for user management and system purpose.
Drop a database
Run the following commands in the terminal below to drop a database.
Select the database that you want to drop.
use <database-name>;
Drop the selected database
db.dropDatabase();
β¨This command will remove all the collections and documents.
You may see the below error if you donβt have enough permission to drop a database.
MongoServerError: not authorized on todo to execute command { dropDatabase: 1, lsid: { i
> d: UUID("1479ef4b-5e3f-42df-aaf8-93234469e6dc") }, $db: "todo" }
I have published an e-book on MongoDB, this e-book will help you learn MongoDB core concepts like queries, documents, embedded documents, operators, etc. with advanced features like CRUD Operations, Bulk Write Operations, GridFS, Indexing, Aggregation Pipeline, Authorization, etc. This e-book includes query examples with each chapter to practice database operations.
Check out here
Top comments (0)