当前位置: 移动技术网 > IT编程>数据库>MongoDB > MongoDB基础入门之创建、删除集合操作

MongoDB基础入门之创建、删除集合操作

2019年03月18日  | 移动技术网IT编程  | 我要评论

创建集合

语法格式

db.createcollection(name, {capped: <boolean>, autoindexid: <boolean>, size: <number>, max <number>})

参数说明

  • name: 要创建的集合的名称
  • options: 可选参数,指定有关内存大小及索引的选项

options参数说明

参数名 参数类型 参数说明
capped 布尔 如果为 true,则创建固定集合。默认为不启用<br />固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。<br />当该值为 true 时,必须指定 size 参数。
autoindexid 布尔 如为 true,自动在 _id 字段创建索引。默认为 false
size 数值 为固定集合指定一个最大值 默认为没有限制。
如果 capped 为 true,也需要指定该字段。
max 数值 指定固定集合中包含文档的最大数量。

_id:mongodb在创建文档的时候会自动生成_id作为主键,但不是自增的
在固定集合在插入文档时,mongodb 首先检查固定集合的 size 字段,然后检查 max 字段。

用法实例

创建固定集合 mycollection,整个集合空间大小 1024000 kb, 文档最大个数为 10000个。

> use test
switched to db test
> db.createcollection("mycollection", {capped : true, autoindexid : true, size : 1024000, max : 10000})
{
 "note" : "the autoindexid option is deprecated and will be removed in a future release",
 "ok" : 1
}
> show collections
mycollection

"note" : "the autoindexid option is deprecated and will be removed in a future release"。官方不赞成给_id创建索引,以后发布的版本会将这个移除

其实,在 mongodb 中,你不需要创建集合。当你插入一些文档时,mongodb 会自动创建集合。

> show collections
mycollection
> db.mycollection2.insert({"name":"缘来是你", "age":27})
writeresult({ "ninserted" : 1 })
> show collections
mycollection
mycollection2
>

删除集合

语法格式

db.collectionname.drop()

collectionname替换为集合名称

返回值

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

实例

> show collections
mycollection
mycollection2
> db.mycollection2.drop()
true
> show collections
mycollection

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网