码迷,mamicode.com
首页 > 数据库 > 详细

MongoDB数据库学习笔记

时间:2015-05-10 20:46:24      阅读:148      评论:0      收藏:0      [点我收藏+]

标签: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”;

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”;


删:
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)    //批量更新所有匹配的数据;

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


查:
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”进行排序;


二、索引


增:
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索引


三、mongoDB安全:


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



本文出自 “方寸小山” 博客,请务必保留此出处http://63638790.blog.51cto.com/513514/1650031

MongoDB数据库学习笔记

标签:mongodb

原文地址:http://63638790.blog.51cto.com/513514/1650031

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!