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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

缘来是你ylh   2021-03-30 我要评论

创建集合

语法格式

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

总结

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

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们