mongodb使用一—数据库和集合

我们使用mongdb数据库一种是使用客户端:Robo 3T 

第二种是使用shell 进入到{mongdbPath}/bin/mongo;如下图:然后直接可以操作mongdb


1.mongodb创建数据库:use database_name;

使用use命令的时候;如果database_name存在的话就会返回当前数据库;如果不存在数据库database_name的话,就会创建数据库database_name;

创建test库 use test;


检查当前数据库: db

> db
test

查询数据库列表 show dbs

> show dbs
admin  1.062GB
local  0.000GB

我们可以看到刚刚新建的数据库test不在列表中,因为这个库中必须要有数据(文档);我们插入一条数据后再看看:

> db.firstTest.insert({"name":"my name is mongodb"})
WriteResult({ "nInserted" : 1 })
> show dbs
admin  1.062GB
local  0.000GB
test   0.000GB

现在我们就可以看到创建的数据库了;

2.删除数据库:db.dropDatabase();

删除当前数据库;如果没有选择数据库(use)的话,默认删除的是test数据库;

> use test
switched to db test
> show dbs
admin  1.062GB
local  0.000GB
test   0.000GB
> use test
switched to db test
> db.dropDatabase()
{ "dropped" : "test", "ok" : 1 }
> show dbs
admin  1.062GB
local  0.000GB

我们看到我们已经删除了我们想要删除的库;

3.创建集合;db.createCollection(name,options);

****name指定的是集合名称;options指定的是集合的配置(内存,索引等配置);也可以不指定options直接使用命令:db.createCollection("name");创建name集合;

1),不指定配置,使用db.createCollection("name");创建name的集合;

> use test
switched to db test
> db.createCollection("firstCollection");
{ "ok" : 1 }
> show collections
firstCollection

2),指定配置,db.createCollection("name","options")

> db.createCollection("optionCollection",{capped:true, autoIndexId:true, size:1024, max:1000});
{
	"note" : "the autoIndexId option is deprecated and will be removed in a future release",
	"ok" : 1
}
> 

options参数说明:

字段类型描述
cappedBooleantrue:启用封闭的集合,上限集合是固定大小的集合,达到最大时会覆盖最旧的条目;如果指定为true必须指定size;
autoIndexIdBooleantrue:则在_id字段自动创建索引;默认为false
size数字上限集合最大大小(以字节为单位);要求capped为true
max数字指定上限集合中允许的最大文档数;
在插入文档时,mongdb首先检查capped,再检查max字段;

我们刚刚在使用数据库时没有创建集合直接插入文档;这样mongdb会给我们自动创建集合;

show collections:查看集合

> show collections
firstCollection
optionCollection

4.删除集合:db.collection_Name.drop();

检查集合 —删除集合—再次检查

> show collections
firstCollection
optionCollection
> db.firstCollection.drop()
true
> show collections
optionCollection


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值