In this post we are going to look at how to drop database and collections. We already covered backup and restores, now that you know how to do that, it is safe to cover dropping collections and databases

Execute the following command, it will create the MultiCollection database if it doesn’t exist already

use MultiCollection

Now create these two collections

db.Blog.insert( { name : "Denis",  age : 20 } )
db.Blog.insert( { name : "Abe",    age : 30 } )
db.Blog.insert( { name : "John",   age : 40 } )
db.Blog.insert( { name : "Xavier", age : 10 } )
db.Blog.insert( { name : "Zen",    age : 50 } )


db.People.insert( { name : "AADenis",  age : 0020 } )
db.People.insert( { name : "AAAbe",    age : 0030 } )
db.People.insert( { name : "AAJohn",   age : 0040 } )
db.People.insert( { name : "AAXavier", age : 0010 } )
db.People.insert( { name : "AAZen",    age : 0050 } )

Now it is time to drop a collection. The syntax is pretty simple it is db.CollectionName.drop(). So if we wanted to drop the Blog collection it would be db.Blog.drop()

Time to try it out, run the following

db.Blog.drop()

The output you get back is true

Now if you do a find on the collection, you won’t get anything back

db.Blog.find()

That was pretty simple. Now let’s see how to drop a database. This is pretty easy as well, it is just db.dropDatabase(). I wished you had to specify the name of the database because you could be in the wrong database when executing the command

Execute this

db.dropDatabase()

Here is the output

{ "dropped" : "MultiCollection", "ok" : 1 }

Just be aware that you are still in the MultiCollection database, you can verify this by executing the following command

db.getName()

And here is the output

MultiCollection

If you now try to do a find for either collection that existed before you won’t get anything back

db.People.find()
db.Blog.find()

Doing a stats command on the database will tell you how many collections you have as well

db.stats()

Here is the output

{
        "db" : "MultiCollection",
        "collections" : 0,
        "objects" : 0,
        "avgObjSize" : 0,
        "dataSize" : 0,
        "storageSize" : 0,
        "numExtents" : 0,
        "indexes" : 0,
        "indexSize" : 0,
        "fileSize" : 0,
        "nsSizeMB" : 0,
        "ok" : 1
}

As you can see everything is pretty much 0

That is all for this post, if you are interested in my other MongoDB posts, you can find them here:

Install MongoDB as a Windows Service

UPSERTs with MongoDB

How to sort results in MongoDB

Indexes in MongoDB: A quick overview

Multidocument updates with MongoDB

MongoDB: How to include and exclude the fields you want in results

MongoDB: How to limit results and how to page through results

MongoDB: How to backup and restore databases

MongoDB: How to restore collections

MongoDB: How to backup all the databases with one command

MongoDB: Exporting data into files