如何在MongoDB中删除或删除集合? [英] How to drop or delete a collection in MongoDB?

查看:69
本文介绍了如何在MongoDB中删除或删除集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MongoDB中删除集合的最佳方法是什么?

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

我正在使用以下内容:

db.collection.drop()

手册中所述:

db.collection.drop()

从数据库中删除一个集合.该方法还删除了与删除的集合关联的索引.该方法提供了包裹放下命令.

Removes 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 drop it from the command line?

推荐答案

因此,以下两种方法都是有效的方法:

So either of these are valid ways to do it:

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

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


例如,对于数据库 mydb 中的集合 mycollection ,您会说:

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

db.mycollection.drop()


这是我对其进行全面测试的方式,它使用集合 hello 创建数据库 mydb .

  • 创建数据库 mydb :

> use mydb
switched to db mydb

  • 创建收藏集 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
    $
    

    这篇关于如何在MongoDB中删除或删除集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆