How to drop or delete a collection in MongoDB?

前端 未结 2 1249
一向
一向 2021-02-03 17:47

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

I am using the following:

db.collection.drop()

As described in the manual:

<
相关标签:
2条回答
  • 2021-02-03 17:47

    To drop a collection 'users' of database 'mydb':

    $ use mydb
    $ db.users.drop()
    
    0 讨论(0)
  • 2021-02-03 18:11

    So either of these are valid ways to do it:

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

    db.<collection>.drop()
    #  ^^^^^^^^^^^^
    

    For example, for a collection mycollection in a database mydb you would say:

    mongo mydb --eval 'db.mycollection.drop()'
    

    db.mycollection.drop()
    

    This is the way I fully tested it, creating a database mydb with a collection hello.

    • Create db mydb:

      > use mydb
      switched to db mydb
      
    • Create a collection mycollection:

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

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

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

      > db.mycollection.find()
      { "_id" : ObjectId("55849b22317df91febf39fa9"), "a" : "b" }
      
    • Delete the collection and make sure it is not present any more:

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

    This also works (I am not repeating the previous commands, since it is just about recreating the database and the collection):

    $ mongo mydb --eval 'db.mycollection.drop()'
    MongoDB shell version: 2.6.10
    connecting to: mydb
    true
    $
    
    0 讨论(0)
提交回复
热议问题