Mongodb drop and create collection

MongoDB is an open-source NoSQL database which means that, unlike relational databases, it does not accept input values in table format. Data is stored in collections and documents since MongoDB is a document-oriented database. Rows in an SQL table have been replaced with documents in MongoDB.

This article assumes that you’ve already installed the MongoDB server on your computer and connected a shell to the server. If you have already done so, we can explore a few features of MongoDB but first, a few terminologies: If not, you can check out the article on how to install MongoDB on Ubuntu.

  • Database – this is a physical container that holds a set of collections. It may contain zero or more collections. There isn’t any limit on how many databases can be hosted in a single server instance, as it can host multiple databases. Its only limit is the virtual memory address space that the underlying operating system can allocate.
  • Collection – a set of MongoDB documents similar to “tables” in relational database systems. A collection holds documents of similar or related purposes. Collections are schema-less, meaning documents within the same collection can have different fields.
  • Document – this is the basic unit for storing data in MongoDB. They are analogous to ROW in traditional relational database systems. Documents are ordered set of key-value pairs, which means that there is an associated value for every key. They are often referred to as “objects.” They are represented in a JSON-like (key-value-pairs) format. Data is stored and queried in a binary representation of JSON-like data known as BSON. An example of this format is shown below:
{
Student_enroll: “foss123”,
grade: ‘B’
}
  • Field – this is the equivalent of columns in relational databases. It is stored in association with its value in key-value pairs. Documents in a collection can have zero or more fields.
  • _id – this is a mandatory field in every MongoDB document. If a user creates a document without an _id field, MongoDB automatically creates the field. _IDs are used to represent unique documents in a collection. They work as documents’ primary keys.

Creating a MongoDB database

Database creation in MongoDB happens implicitly when you try to use a database. To create a database, type the following in the mongo shell;

> use fossDB

Output:

Mongodb drop and create collection
Create database

Note: To open the Mongo shell, run the command below:

mongo

MongoDB will first check to confirm if a database named fossDB is present. If not, it will then create a new one to be used. The Mongo shell then switches to fossDB. This means that every collection and document created, updated, or read will be from this database unless specified otherwise.

To print what database you are in right now, you use the command > db. To list all the databases available and created, you use the command >show. An example of these commands in use are shown below;

>db
fossDB
>show dbs
admin  0.000GB
config  0.000GB
local    0.000GB
mydb   0.000GB

Output:

Mongodb drop and create collection
Show current databases

Note: Do not interfere with the admin and config databases as Mongo uses them for administrative purposes.

Creating a MongoDB collection

To create a collection, first, make sure that you are in the correct database that you intend to create the collection in. There are two ways in creating a collection which are:

1. Creating a collection explicitly

Use the command below:

>db.createCollection("Collection1");
{"ok":1}

Output:

Mongodb drop and create collection
Create collection

This command will then create a collection named Collection1

2. Inserting a document into a new collection

You can quickly try inserting a document into a non-existing collection. This will prompt Mongo to create a new collection for you. Do note that while this is convenient in terms of programmatically creating collections, if you are using Mongo shell and make a typo somewhere while inserting a document, the document may end up in a new database that is unbeknownst to you.

The syntax for creating a new collection is;

db.collection_name.insert(document); 

To create a collection Collection2 in fossDB database, use the following command:

> db.Collection2.insert({name: "Alex",key: "value",age: 20});

Output:

Mongodb drop and create collection
Create a new collection and insert data

In this example, the document part is represented by the following JSON string:

{
name: "Alex",
key: "value"
age: 20
}

These are the key-value pairs typical of a JSON string. The “name” is the key, and “Alex” is the value. A user can have multiple documents in this collection with the key name and a different value, say Max.

Use the command below to list all the collections inside a database:

> show collections
Collection1
Collection2

Output:

Mongodb drop and create collection
Display collections

From the output, you will notice that both collections have been created. You are confident that you can add a new document into a collection.

Showing collections

If you have not noticed, we have been using the show keyword quite a lot while discussing the other commands. To recap on this, the command for showing collections and databases are:

>show collections
>show dbs

Output:

Mongodb drop and create collection
Shows databases and collections

In conjunction with the command db, these commands are used to print the current database and are pretty handy while interacting with the Mongo shell.

Dropping MongoDB Collections and Database

The drop command is a keyword that we have not touched on in this article. It is a command used to remove collections or entire databases from a user’s Mongo server. To drop, the following syntax will take you through the process.

1. Dropping collections

We will eliminate the collection “Collection2” that we created earlier. This is done by using the command below:

>db.Collection2.drop()

Output:

Mongodb drop and create collection
Drop collections

To verify that the collection has been deleted, you can use the show collections command to list the remaining collections. You will notice that there will be one collection missing from the list.

2. Dropping Databases

Before you run the command to drop the database, you should check that you are in the correct database, or else you might get rid of the wrong database and end up losing Valuable data that you did not intend to delete. In this example, we will be dropping the database fossDB that we had created earlier. Let’s make sure that we are in the correct database using the command below:

>db
fossDB

Output:

Mongodb drop and create collection
Database

let’s then drop the database using the command below:

>db.dropDatabase();

Output:

Mongodb drop and create collection
Drop database

Below we are going to present various SQL terms and their corresponding MongoDB terms;

SQL termsMongoDB terms
Database Database
Table Collection
Index Index
Row Document / BSON document
Column Field
Table joins Embedded documents and linking
Primary key – in SQL, this specifies any unique column or column combination Primary key – this key is automatically set to the _id field in MongoDB

Conclusion

MongoDB has attained massive popularity in the developers’ world because of the JSON-like representation, scalability, ease, and dynamic way of creating documents. This article has discussed the three commands used in the MongoDB shell. We hope that this article has helped you understand these commands better. If you are looking for a database to be used in a project for data-heavy lifting, MongoDB is a good option that you might want to consider. 

How do I create and drop a collection in MongoDB?

4 Answers.
Create db mydb : > use mydb switched to db mydb..
Create a collection mycollection : > db. createCollection("mycollection") { "ok" : 1 }.
Show all the collections there: > db. ... .
Insert some dummy data: > db. ... .
Make sure it was inserted: > db. ... .
Delete the collection and make sure it is not present any more: > db..

How do I drop a collection in MongoDB?

First, check the available collections into your database mydb..
>use mydb switched to db mydb >show collections mycol mycollection system. indexes tutorialspoint > Now drop the collection with the name mycollection..
>db. mycollection. drop() true > ... .
>show collections mycol system. indexes tutorialspoint >.

What is db collection drop ()?

In MongoDB, db. collection. drop() method is used to drop a collection from a database. It completely removes a collection from the database and does not leave any indexes associated with the dropped collections.

What is the difference between drop and delete in MongoDB?

DELETE is a Data Manipulation Language command, DML command and is used to remove tuples/records from a relation/table. Whereas DROP is a Data Definition Language, DDL command and is used to remove named elements of schema like relations/table, constraints or entire schema.