monggodb学习系列:1,mongodb入门
背景:先问自己三W,WHAT, WHEN,HOW?
WHAT: mongodb是什么?
概念 | mongodb是一个高可用,分布式,模式灵活的文档数据库。底层使用C++编写,是一种介于关系数据库和NoSql数据库之间的数据库。在海量读写的情况下有极高的查询性能 |
高可用 | 多地复制,自动故障转移,查询监视 |
分布式 | 自动分片,支持云级别的伸缩 |
模式灵活 | 扩展方便,支持动态查询,面向集合操作,支持索引 |
文档 | Bson结构, 高效传输 |
Nosql : not only sql,非关系数据库,在web2.0时代,为了解决一大三高的问题引入而留下的数据库概念,代表作有 mongodb, redis,
nosql 具有硬件便宜,性能高,无过多操作,开源的特点;
跟关系数据库相关概念的对比:
对比项目 | 关系模型 | 文档模型 |
数据对象 | 重复的部分使用单独的表来存储 | 使用富文档包含所有信息 |
数据库 | db | db |
表 | table | collection |
行 | row | document |
外键 | forignkey | reference |
连接 | join | lookup |
事务 | 支持多表事务控制 | 对文档的操作可以保证原子性 |
WHEN: 什么时候适合用mongodb,什么时候不适合使用mongodb?
适合场景 | 说明 |
网站数据 | 在海量的更新查询场景下具备极高的查询性能; |
缓存 | |
大尺寸低价值数据 | |
高伸缩性场景 | 内置支持了MapReduce |
存储的是对象或者Json | 原生存储格式为Bson |
使用的案例: 国内的有淘宝,视觉中国,大众点评, 国外的有sourcefore, github;
慎用: 在事务要求下较高的场景下慎用;
HOW: mongodb怎么使用?怎么去管理? 怎么去搭建集群,解决现在海量系统的三高一大问题?
三高: 高并发,高扩展,高可用 ;
一大:大数据,海量数据;
本次分享内容目录:
- mongodb的安装;
- mongodb的基本命令熟悉;
- 使用java驱动使用mongodb;
- 查询优化器的工具熟悉;
- 入门小结
mongodb的安装
顺序 | 步骤说明 | |
1 | 下载,解压到本地磁盘; | https://www.mongodb.com/download-center?jmp=nav |
2 | 新建数据库和日志目录; | d:\mongodb\db d:\mongodb\db\log |
3 | 启动mongodb | 进入mongodb的安装目录下的bin路径下 mongod --dbpath=d:\mongodb\db --logpath=d:\mongodb\db\log --install |
4 | 设置为系统服务,并启动 | 启动服务 net start mongodb |
5 | 客户端连接 | 在bin路径下 输入 mongo, 即连接默认数据库test |
上个截图:(如果经常使用mongodb的命令行窗口,自己把bin路径增加到path目录中)
mongodb的基本命令熟悉;
1, show dbs; //查看mongodb中所有的数据库;
2, db.version();// 查看db的版本
3,db.stats();//查看当前db的状态;
4,db.serverStatus();//查看服务器的状态
5,db.repairDatabase();//修复数据库,压缩预分配空间,整理碎片等;
6,db.hostInfo();//本服务器的信息;
7,db.isMaster();//是否是主服务器
8,db.currentOp();//查看目前在执行的操作
8.1 use dbName;// 切换db
8.2 db.dropDatabase(); //删除db
对数据表的操作
9,db.getCollectionNames();//查看数据库所有的表:
10,插入
db.users.save({"username":"abcdefgk","password":"abcabc","lang":"En","age":18});//插入数据
11,查询
12,删除
db.users.remove({"_id":ObjectId("58184bbff7507c0558153923")});
13,修改
db.users.update({"_id" : ObjectId("58184bbff7507c0558153922")},{$set:{"lang":"
update"}},false,true);
14, 查询并修改
> db.users.findAndModify({query:{lang:{$eq:"en"}},update:{$set:{"lang":"fuck"}}}
);
15,查看索引,索引大小;
db.users.getIndexes();
db.users.totalIndexSize();//索引的总大小
db.users.reIndex();//读取当前表的所有索引
16,建立索引
17,删除索引
18,语句块操作
循环插入数据;
db.users.find({age: {$lte: 28}}, {age: false}).forEach(printjson);
19,查询之前的错误
20,查询语法
find(condition1,row, ).sort(conditon2).skip(num1).limit(num2).pretty()
condition: 条件,里面可以放条件,正则表达式,
skip(num1) 略过多少条数据
limit(num2) 取前多少条数据
pretty() json格式展示
按照范围来搜索:
按照正则来搜索:
选择显示的行
排序 1为升,-1为降
使用java驱动使用mongodb;
本质: 把相关的mongodb的命令行命令进行封装,提供java接口;
package db.mongo.dao;import com.google.common.collect.Lists; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import db.mongo.core.MongoDatabaseHelp; import db.mongo.model.User; import org.bson.Document; import org.bson.types.ObjectId;import java.util.List;/** * Created by carter on 2016/11/1. */ public class UserDao { MongoCollection documentMongoCollection; public UserDao() { documentMongoCollection = MongoDatabaseHelp.getInstance().getCollection("users"); } public void create(User user) { documentMongoCollection.insertOne(new Document("username",user.getUsername()).append("password",user.getPassword()).append("lang",user.getLang()).append("age",user.getAge())); } public boolean delete(String _id) { return documentMongoCollection.findOneAndDelete(new Document("_id",new ObjectId(_id))).size()>0; } public boolean update(User user) { // if(user.getAge()>0) // { // return documentMongoCollection.updateOne(new Document("_id",new ObjectId(user.get_id())), // new Document("username",user.getUsername()).append("password",user.getPassword()).append("lang",user.getLang()).append("age",user.getAge())).getModifiedCount()>0; // }else // { return documentMongoCollection.updateOne(new Document("_id",new ObjectId(user.get_id())), new Document("$set",new Document("username",user.getUsername()).append("password",user.getPassword()).append("lang",user.getLang()).append("age",user.getAge()))).getModifiedCount()>0;// } } public User find(String _id) { FindIterable result = documentMongoCollection.find(new Document("_id",new ObjectId(_id))); Document document = result.iterator().tryNext(); if(null != document ) { User user = new User(); user.set_id(document.getObjectId("_id").toString()); user.setLang(document.getString("lang")); user.setUsername(document.getString("username")); user.setPassword(document.getString("password")); user.setAge(document.containsKey("age")?Integer.parseInt(String.valueOf(document.get("age"))):0); return user; } return new User(); } public List query() { MongoCursor mongoCursor= documentMongoCollection.find().iterator(); List userList = Lists.newLinkedList(); while (mongoCursor.hasNext()) { Document document = mongoCursor.next(); User user = new User(); user.set_id(document.getObjectId("_id").toString()); user.setLang(document.getString("lang")); user.setUsername(document.getString("username")); user.setPassword(document.getString("password")); user.setAge(document.containsKey("age")?Integer.parseInt(String.valueOf(document.get("age"))):0); userList.add(user); } mongoCursor.close(); return userList; } public List query(int pageIndex) { MongoCursor mongoCursor= documentMongoCollection.find().skip((pageIndex-1)*30).limit(30).iterator(); List userList = Lists.newLinkedList(); while (mongoCursor.hasNext()) { Document document = mongoCursor.next(); User user = new User(); user.set_id(document.getObjectId("_id").toString()); user.setLang(document.getString("lang")); user.setUsername(document.getString("username")); user.setPassword(document.getString("password")); user.setAge(document.containsKey("age")?Integer.parseInt(String.valueOf(document.get("age"))):0); userList.add(user); } mongoCursor.close(); return userList; } public long count() { return documentMongoCollection.count(); } } |
package db.mongo.core;import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.client.MongoDatabase;/** * Created by carter on 2016/11/1. */ public class MongoDatabaseHelp { private static MongoDatabaseHelp ourInstance = new MongoDatabaseHelp(); public static MongoDatabase getInstance() { if(null == mongoDatabase) { MongoClient mongoClient = new MongoClient("172.16.42.22",MongoClientOptions.builder().connectionsPerHost(100)//每个主机的连接数 .threadsAllowedToBlockForConnectionMultiplier(100)//线程队列数,它以上面connectionsPerHost值相乘的结果就是线程队列最大值。如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。 .maxWaitTime(10)//最大等待连接的线程阻塞时间 .connectTimeout(15*1000)//连接超时的毫秒。0是默认和无限 .socketTimeout(15*1000)//socket超时。0是默认和无限 .build()); mongoDatabase = mongoClient.getDatabase("blog"); } return ourInstance.mongoDatabase; } private static MongoDatabase mongoDatabase; private MongoDatabaseHelp() { } } |
查询优化器的工具熟悉;
使用mongodb官网提供的查询分析工具 MongoDB Compass
优化步骤:
可以观察某查询,是否走了索引;
入门小结
通过本次小结,知道了什么是mongodb, mongodb在什么场景下使用,以及怎么使用mongodb,分命令行和java程序去使用;
http://note.youdao.com/share/?id=fa62cd2386f253af68a7e29c6638f158&type=note#/
转载于:https://my.oschina.net/mifans/blog/818304