mongodb的集合操作

MongoDB 创建集合

1.手动创建:

语法格式:

db.createCollection(name, options)

参数说明:

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

options 可以是如下参数:

字段类型描述
capped 布尔 (可选)如果为 true,则创建固定集合。固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。
当该值为 true 时,必须指定 size 参数。
autoIndexId 布尔 (可选)如为 true,自动在 _id 字段创建索引。默认为 false。
size 数值 (可选)为固定集合指定一个最大值(以字节计)。
如果 capped 为 true,也需要指定该字段。
max 数值 (可选)指定固定集合中包含文档的最大数

 例如:在exam表中创建colle1集合:

> use exam
switched to db exam
> db.createCollection("colle1")
{ "ok" : 1 }
> show collections #查看当前数据库的集合
colle1
system.indexes

创建固定集合 mycol,整个集合空间大小 6142800 KB, 文档最大个数为 10000 个。

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

2.在 MongoDB 中,你不需要创建集合。当你插入一些文档时,MongoDB 会自动创建集合。

> show collections
colle1
system.indexes
> db.exam.insert({"name111" : "菜鸟教程"})
WriteResult({ "nInserted" : 1 })
> show collections
colle1
exam
system.indexes

 

MongoDB 删除集合

语法格式:

db.collection.drop()

返回值

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

例如:查看所有的集合并删除其中一个集合

> show collections
colle1
exam
system.indexes
> show tables
colle1
exam
system.indexes
> db.colle1.drop()
true
> show tables
exam
system.indexes
>

   查看当前数据的集合可以用show collections或者show tables

原文地址:https://www.cnblogs.com/qlqwjy/p/8626659.html