如何删除或删除 MongoDB 中的集合?
How to drop or delete a collection in MongoDB?
在 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
中的 collection mycollection
你会说:
mongo mydb --eval 'db.mycollection.drop()'
db.mycollection.drop()
这是我完全测试它的方式,创建一个数据库 mydb
collection hello
.
创建数据库mydb
:
> use mydb
switched to db mydb
创建 collection mycollection
:
> db.createCollection("mycollection")
{ "ok" : 1 }
显示那里的所有 collection:
> db.getCollectionNames()
[ "mycollection", "system.indexes" ]
插入一些虚拟数据:
> db.mycollection.insert({'a':'b'})
WriteResult({ "nInserted" : 1 })
确保已插入:
> db.mycollection.find()
{ "_id" : ObjectId("55849b22317df91febf39fa9"), "a" : "b" }
删除 collection 并确保它不再存在:
> db.mycollection.drop()
true
> db.getCollectionNames()
[ "system.indexes" ]
这也有效(我没有重复前面的命令,因为它只是重新创建数据库和 collection):
$ mongo mydb --eval 'db.mycollection.drop()'
MongoDB shell version: 2.6.10
connecting to: mydb
true
$
删除数据库 mydb
的集合 users
:
> use mydb
> db.users.drop()
--eval "db.getCollection('collection').drop()"
在 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
中的 collection mycollection
你会说:
mongo mydb --eval 'db.mycollection.drop()'
db.mycollection.drop()
这是我完全测试它的方式,创建一个数据库 mydb
collection hello
.
创建数据库
mydb
:> use mydb switched to db mydb
创建 collection
mycollection
:> db.createCollection("mycollection") { "ok" : 1 }
显示那里的所有 collection:
> db.getCollectionNames() [ "mycollection", "system.indexes" ]
插入一些虚拟数据:
> db.mycollection.insert({'a':'b'}) WriteResult({ "nInserted" : 1 })
确保已插入:
> db.mycollection.find() { "_id" : ObjectId("55849b22317df91febf39fa9"), "a" : "b" }
删除 collection 并确保它不再存在:
> db.mycollection.drop() true > db.getCollectionNames() [ "system.indexes" ]
这也有效(我没有重复前面的命令,因为它只是重新创建数据库和 collection):
$ mongo mydb --eval 'db.mycollection.drop()'
MongoDB shell version: 2.6.10
connecting to: mydb
true
$
删除数据库 mydb
的集合 users
:
> use mydb
> db.users.drop()
--eval "db.getCollection('collection').drop()"