MongoDB基本操作

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参数说明:

字段 类型 描述
capped Boolean true:启用封闭的集合,上限集合是固定大小的集合,达到最大时会覆盖最旧的条目;如果指定为true必须指定size;
autoIndexId Boolean true:则在_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

---------------------
作者:梧_桐
来源:CSDN
原文:https://blog.csdn.net/qizonghui/article/details/80857114
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2019-01-16 15:50  feng_yy  阅读(248)  评论(0编辑  收藏  举报