Search This Blog

2024/04/20

MongoDb:Drop database,Drop Table & truncate table

In SQL we are familar with drop table,database,truncate table.

Same things are applicable to mongodb.

DROP Collection:

In MongoDB, you can drop a collection using the drop() method.

Lets first create a collection as

db.student.insertMany([
{
name:"sangram"
},
{
name:"sagar"
},
{
name:"sachin"
}
])

Now if you check the
show tables;

It will be shown in output of this query as one of the
collection/table in this database.

Now drop the collection/table by
db.student.drop()

Again run
show tables;
Now student will not be in output of this query.

DROP DATABASE:

To drop database in mongo first use that database then run db.dropDatabase()
e.g.
First lets create our own DB for purpose of dropping it so that we can then
drop it without worrying about others.

use AppDb;

Add a collection to this Database

db.student.insertMany([
{
name:"sangram"
},
{
name:"sagar"
},
{
name:"sachin"
}
])

Now if you run
show tables;
Output:
student

Now we are going to drop our current database.

db.dropDatabase()
Output:
we get no output
Truncate Collection:
For truncation purpose also we will use same database.
So
use AppDb;

Add a collection to this Database
db.student.insertMany([
{
name:"sangram"
},
{
name:"sagar"
},
{
name:"sachin"
}
])

Now if you run find you will get 3 documents.
db.student.find({});

Output:
[
{ _id: ObjectId('6623c6b24ce833ee7bef634e'), name: 'sangram' },
{ _id: ObjectId('6623c6b24ce833ee7bef634f'), name: 'sagar' },
{ _id: ObjectId('6623c6b24ce833ee7bef6350'), name: 'sachin' }
]

Now lets run command for truncate
db.student.deleteMany({})
Now if you run
db.student.find({});
Output:
No output as no document in our collection,the collection is truncated.

No comments:

Post a Comment