Delete Table in MongoDB




Asked on September 20, 2019
In MongoDB
1. How to delete selected data from table?
2. How to delete complete data from table?
3. How to drop the table?



Replied on September 20, 2019
1. Suppose your database name is myDB. Go to your database. 
> use myDB

2. Display all tables.
> show tables

The output will be all tables available in myDB database.

3. Suppose you have a employee table in you MongoDB database. Now display all data of this table using find().
> db.employee.find()
{ "_id" : 1, "name" : "Ram", "age" : 20, "_class" : "com.test.mongodb.entity.Employee" }
{ "_id" : 2, "name" : "Shyam", "age" : 19, "_class" : "com.test.mongodb.entity.Employee" }
{ "_id" : 3, "name" : "Mohan", "age" : 20, "_class" : "com.test.mongodb.entity.Employee" }
{ "_id" : 4, "name" : "Krishn", "age" : 20, "_class" : "com.test.mongodb.entity.Employee" }

4. Delete selected data from table: 

Use remove() and pass the criteria to delete data.
> db.employee.remove({name:'Ram'})
WriteResult({ "nRemoved" : 1 })

Check the data in table. You will observe that those data will be deleted that meets the criteria.
> db.employee.find()
{ "_id" : 2, "name" : "Shyam", "age" : 19, "_class" : "com.test.mongodb.entity.Employee" }
{ "_id" : 3, "name" : "Mohan", "age" : 20, "_class" : "com.test.mongodb.entity.Employee" }
{ "_id" : 4, "name" : "Krishn", "age" : 20, "_class" : "com.test.mongodb.entity.Employee" }

5. Delete complete data from table:
To delete all rows of the table, keep the criteria blank.

> db.employee.remove({})
WriteResult({ "nRemoved" : 3 })

If we try to find the data from the table, we will get nothing.
> db.employee.find()

6. Drop the table:
To drop the table use drop()

> db.employee.drop()
true

In our demo, I created only one table in database. As it is dropped, now there is no table in database.

> show tables

It will show nothing.



Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us