MongoDB数据库学习笔记


1、Mongodb数据库之增删改查mongodb


show databases
show dbs    //显示数据库;数据库

show tables   
show collections    //查示表或者集合;数组

use imooc  //使用或建立数据库imooc;安全


增:
use imooc
db.imooc_collection.insert({x:1})    //往集合名“imooc_collection”插入单条数据“x:1”;ide

db.imooc_collection.insert({x:2})    //往集合名“imooc_collection”插入单条数据“x:2”;
db.imooc_collection.insert({x:100,y:100,z:100})    //往集合名“imooc_collection”插入多字段单条数据;
for(i=3;i<100;i++)db.imooc_collection.insert({x:i})    //往集合名“imooc_collection”批量插入数据“x:3-99”;spa


删:
db.imooc_collection.remove({c:2})    //删除集合或表匹配的数据(必须传递参数,不然报错);
db.imooc_collection.drop()    //删除集合或表;排序

use imooc
db.dropDatabase()    //删除数据库imooc;索引


改:
db.imooc_collection.update({x:1},{x:999})    //更改集合名“imooc_collection”里“x:1”为“x:999”;
db.imooc_collection.update({z:100},{$set:{y:99}})    //当查找“z:100”时,只更新y字段为“y:99”;
db.imooc_collection.update({y:100},{y:999},true)    //当查找的数据不存在时,插入一条数据;
db.imooc_collection.update({c:1},{$set:{c:2}},false,true)    //批量更新全部匹配的数据;ip

注:mongodb默认只更新查找到的第一条数据,目的是防止update误操做;rem


查:
db.imooc_collection.find()    //查询集合名“imooc_collection”里的全部数据内容;
db.imooc_collection.find().count()    //统计集合名“imooc_collection”里的全部数据内容的条数;
db.imooc_collection.find().skip(3)    //查询过滤前3条数据;
db.imooc_collection.find().limit(10)    //查询限制只显示前10条数据;
db.imooc_collection.find().sort({x:1})    //查询使用“x”进行排序;


2、索引


增:
db.collection.ensureIndex()

删:
db.collection.dropIndex("index name")

改:

查:
db.collection.getIndexes()

1._id索引:

use imooc
db.table2.insert({x:1})
db.table2.getIndexes()    //_id索引是插入数据时,默认自动建立的惟一索引(该命令为查询集合内的索引);

2.单键索引:

db.table2.ensureIndex({x:1})    //建立“x:1”的单键索引,查询条件为一个值时即为单键索引;


3.多键索引:

db.table2.insert({x:[1,2,3,4,5]})    //插入一个数组,再建立的索引即为多键索引;


4.复合索引:

db.table2.ensureIndex({x:1,y:2})    //查询条件不仅一个时建立的索引即为复合索引;


5.过时索引:

db.table2.insert({time:new Date()})    //插入time:当期时间的一条数据;
db.table2.ensureIndex({time:1},{expireAfterSeconds:30})    //建立键值为time,过时时间为30后的过时索引;

注:数据必须是ISOdate或者ISODate数组,才能自动删除;每60秒执行检测一次;


6.全文索引:

db.table2.ensureIndex({key:"text"})
db.table2.ensureIndex({key_1:"text",ke_2:"text"})
db.table2.ensureIndex({"$**":"text"})    //建立全文索引的三种方法;

db.table2.find({$text:{$search:"aa"}})
db.table2.find({$text:{$search:"aa bb cc"}})
db.table2.find({$text:{$search:"aa bb -cc"}})
db.table2.find({$text:{$search:"\"aa\" \"bb\""}})
db.table2.find({text:{$search:"aa bb"}},{score:{$meta:"textScore"}}).sort({score:{$meta:"textScore"}})    //使用全

文索引的五种方法;

注:全文索引只能指定一个“text”;MongoDB暂不支持中文;

索引重要属性:
1.名字(name);
2.惟一性(unique);
3.稀疏性(sparse);
4.是否认时删除(expireAfterSeconds);


7.地理位置索引:

7.1 2d索引

7.2 2dsphere索引


3、mongoDB安全:


1.开启权限认证;2.建立用户;3.建立用户角色;

相关文章
相关标签/搜索