Section 7.1: 创建集合
首先选择或创建一个数据库。
> use mydb
switched to db mydb
使用 db.createCollection(“yourCollectionName”) 方法,您可以显式地创建集合。
> db.createCollection("newCollection1")
{ "ok" : 1 }
使用 show collections 命令查看数据库中的所有收藏。
> show collections
newCollection1
system.indexes
>
db.createCollection()`方法有以下参数:
| Parameter | Type | Description |
|---|---|---|
| name | string | 要创建的集合名称。 |
| options | document | 可选。用于创建上限集合或在新集合中预先分配空间的配置选项。 |
下面的示例显示了 createCollection() 方法的语法和几个重要选项
> db.createCollection("newCollection4", {capped :true, autoIndexId : true, size : 6142800, max :
10000})
{ "ok" : 1 }
如果 db.collection.insert() 和 db.collection.createIndex() 操作还不存在,它们都会创建各自的集合。
> db.newCollection2.insert({name : "XXX"})
> db.newCollection3.createIndex({accountNo : 1})
现在,使用 show collections 命令显示所有集合
> show collections
newCollection1
newCollection2
newCollection3
newCollection4
system.indexes
如果要查看插入的文档,请使用 find() 命令。
> db.newCollection2.find()
{ "_id" : ObjectId("58f26876cabafaeb509e9c1f"), "name" : "XXX" }
Section 7.2: 删除集合
MongoDB 的 db.collection.drop() 用于从数据库中删除某个集合。
首先,检查数据库 mydb 中的可用集合。
> use mydb
switched to db mydb
> show collections
newCollection1
newCollection2
newCollection3
system.indexes
现在删除名为 newCollection1 的集合。
> db.newCollection1.drop()
true
注意:如果成功删除了集合,该方法将返回 true,否则将返回 false。
再次检查数据库中的集合列表。
> show collections
newCollection2
newCollection3
system.indexes
参考: MongoDB drop() 方法。