MongoDB 集合管理

创建集合

MongoDB 中使用 createCollection() 方法来创建集合。语法格式:

db.createCollection(name, options)

说明:

  • name: 要创建的集合名称

  • options: 可选参数, 指定有关内存大小及索引的选项。options 可以是如下参数:

MongoDB 集合管理

注意:在插入文档时,MongoDB 首先检查固定集合的 size 字段,然后检查 max 字段。

实例:在 test 数据库中创建 hxstrive 集合。例如:

test> db.createCollection("hxstrive")
{ ok: 1 }

如果要查看已有集合,可以使用 show collections 或 show tables 命令。例如:

test> show collections
hxstrive

test> show tables
hxstrive

下面是带有几个关键参数的 createCollection() 的用法,如创建固定集合 mycol,整个集合空间大小 6142800 B, 文档最大个数为 10000 个。例如:

test> db.createCollection("mycol", { capped: true, autoIndexId: true, size: 6142800, max: 10000 })
{ ok: 1 }

注意:在 MongoDB 中,集合可以不用手动创建。当你插入一些文档到集合时,MongoDB 会自动创建集合。例如:

test> show collections
hxstrive
mycol

test> db.mycol2.insert({name:"自动创建集合"})
DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.
{
 acknowledged: true,
 insertedIds: { '0': ObjectId("64e6d97210366fa87109a11d") }
}

test> show collections
hxstrive
mycol
mycol2

删除集合

MongoDB 中使用 drop() 方法来删除集合。语法格式:

db.collection.drop()

注意:如果成功删除选定集合,则 drop() 方法返回 true,否则返回 false。

实例:在数据库 test 中,我们可以先通过 show collections 命令查看已存在的集合。例如:

test> show collections
hxstrive
mycol
mycol2

接着删除集合 mycol2。例如:

test> db.mycol2.drop()
true

通过 show collections 再次查看 test 数据库中的集合。例如:

test> show collections
hxstrive
mycol

从结果中可以看出 mycol2 集合已被删除。

查询集合

MongoDB 中使用 show collections 命令查看当前数据库中所有的集合列表,例如:

test> show collections
hxstrive
mycol
mycol2
说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号