How to delete a collection in MongoDB?

What is the best way to delete a collection in MongoDB?

I am using the following:

db.collection.drop() 

As described in the manual :

db.collection.drop ()

Deletes a collection from the database. The method also removes any indexes associated with the dropped collection. The method provides a wrapper around the drop command.

But how can I remove it from the command line?

+34
collections mongodb
source share
2 answers

Thus, any of these methods is valid:

 mongo <dbname> --eval 'db.<collection>.drop()' db.<collection>.drop() 

So I tested it completely by creating a mytest database with the hello collection.

  • Create db mytest :

     > use mytest switched to db mytest 
  • Create a hello collection:

     > db.createCollection("hello") { "ok" : 1 } 
  • Show all collections there:

     > db.getCollectionNames() [ "hello", "system.indexes" ] 
  • Insert some dummy data:

     > db.hello.insert({'a':'b'}) WriteResult({ "nInserted" : 1 }) 
  • Make sure it is inserted:

     > db.hello.find() { "_id" : ObjectId("55849b22317df91febf39fa9"), "a" : "b" } 
  • Delete the collection and make sure that it is no longer there:

     > db.hello.drop() true > db.getCollectionNames() [ "system.indexes" ] 

This also works (I do not repeat the previous commands, since this is just a recreation of the database and collection):

 $ mongo mytest --eval 'db.hello.drop()' MongoDB shell version: 2.6.10 connecting to: mytest true $ 
+63
source share

To remove the 'users' collection from the 'mydb' database:

 $ use mydb $ db.users.drop() 
+1
source share

All Articles