gpt4 book ai didi

mongodb - 如何在 MongoDB 中删除或删除集合?

转载 作者:IT老高 更新时间:2023-10-28 11:05:49 30 4
gpt4 key购买 nike

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

我正在使用以下内容:

db.collection.drop()

the manual 中所述:

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.

但是我怎样才能从命令行中删除它呢?

最佳答案

所以这些都是有效的方法:

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 }
  • 在那里显示所有收藏:

    > db.getCollectionNames()
    [ "mycollection", "system.indexes" ]
  • 插入一些虚拟数据:

    > db.mycollection.insert({'a':'b'})
    WriteResult({ "nInserted" : 1 })
  • 确保已插入:

    > db.mycollection.find()
    { "_id" : ObjectId("55849b22317df91febf39fa9"), "a" : "b" }
  • 删除该集合并确保它不再存在:

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

这也有效(我不重复前面的命令,因为它只是重新创建数据库和集合):

$ mongo mydb --eval 'db.mycollection.drop()'
MongoDB shell version: 2.6.10
connecting to: mydb
true
$

关于mongodb - 如何在 MongoDB 中删除或删除集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30948151/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com