一、创建集合
本章节我们为大家介绍如何使用 MongoDB 来创建集合。
MongoDB 中使用 createCollection() 方法来创建集合。
语法格式:
1 | db.createCollection( name , options) |
参数说明:
- name: 要创建的集合名称
- options: 可选参数, 指定有关内存大小及索引的选项
options 可以是如下参数:
在插入文档时,MongoDB 首先检查固定集合的 size 字段,然后检查 max 字段。
实例
在 test 数据库中创建 runoob 集合:
1 2 3 4 5 | > use test switched to db test > db.createCollection( "runoob" ) { "ok" : 1 } > |
如果要查看已有集合,可以使用 show collections 或 show tables 命令:
1 2 3 | > show collections runoob system.indexes |
下面是带有几个关键参数的 createCollection() 的用法:
创建固定集合 mycol,整个集合空间大小 6142800 KB, 文档最大个数为 10000 个。
1 2 3 4 | > db.createCollection( "mycol" , { capped : true , autoIndexId : true , size : 6142800, max : 10000 } ) { "ok" : 1 } > |
在 MongoDB 中,你不需要创建集合。当你插入一些文档时,MongoDB 会自动创建集合。
1 2 3 4 | > db.mycol2. insert ({ "name" : "菜鸟教程" }) > show collections mycol2 ... |
二、删除集合
本章节我们为大家介绍如何使用 MongoDB 来删除集合。
MongoDB 中使用 drop() 方法来删除集合。
语法格式:
1 | db.collection. drop () |
返回值
如果成功删除选定集合,则 drop() 方法返回 true,否则返回 false。
实例
在数据库 mydb 中,我们可以先通过 show collections 命令查看已存在的集合:
1 2 3 4 5 6 7 8 | >use mydb switched to db mydb >show collections mycol mycol2 system.indexes runoob > |
接着删除集合 mycol2 :
1 2 3 | >db.mycol2. drop () true > |
通过 show collections 再次查看数据库 mydb 中的集合:
1 2 3 4 5 | >show collections mycol system.indexes runoob > |
从结果中可以看出 mycol2 集合已被删除。
到此这篇关于MongoDB集合操作的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持IT俱乐部。