分布式系列十五: MongoDB数据库

MongoDB 是基于分布式文件存储的数据库. 开发语言是C++. 具有高性能,可扩展的特点. 是NoSql中最像关系数据库的.

什么是NoSql

NoSQL 是 Not only SQL 的缩写. 是对不同于传统的关系数据库的数据管理系统的统称. 一般用来存储超大规模数据, 且数据不需要有具体的模式, 可以横向扩展.

与关系数据库的对比

  • RDB 存储结构化数据, 数据结构之间可能存在约束; NoSQL无固定模式,一般采用k-v方式, 无表关联等约束.
  • RDB 有规范的 SQL 语言; NoSQL无
  • RDB 有严格一致性和事务特征; NoSQL只要求最终一致性, 无事务属性
  • 比 RDB 具有高性能, 可扩展和可伸缩性

NoSQL 分类

  • 列存储: HBase ; Cassandra ; HyperTable

    按列查询性能有优势; 按列存储方便压缩

  • 文档存储: MongoDB, CounchDB

    文档结构存储, 类似Json, 可以为某些字段建立索引. 类似关系数据库.

  • key-value 存储: MemCache,Redis

  • 图存储: Neo4J

  • 对象存储:

  • XML数据库

CAP 理论

满足 AP.

MongoDB 与 RDB 的概念对比

关系数据库 MongoDB 说明
DataBase DataBase 数据库
Table Collection 数据表/集合
Row Document 数据行/文档
Column Field 数据列/数据字段
Index Index 索引
Primary Key Object ID 主键/MongoDB对象标识

MongoDB 存储的格式是BSON, 是二进制的Json.

MongoDB 的数据类型

略,

MongoDB 集群

包含: RouteServer(路由 对应的执行文件为Mongos.exe), ConfigServer(配置) , ReplicaSets (副本集合 对应的执行文件为mongod.exe), 仲裁Server

集群模式

  • 主从 master/slave 与mysql主从, 或者redis主从一样
  • 副本集 master/slave/arbiter(仲裁) 类似redis的sentinel机制
  • 混合模式

步骤

  • 主从配置(主节点挂掉就不可用)

mongo.cfg 文件中

# 主配置
master=true
source=192.1.68.1.111:21897

# 从配置
slave=true
source=192.1.68.1.111:21897
  • 副本集一(仲裁节点单点故障会导致服务不可用)
replset=shard002  #同一集中的配置一样

执行命令:

cfg={_id:"shard001",members:{{_id:0,host:'192.168.1.111:27897',priority:9},{_id:0,host:'192.168.1.112:27897',priority:1},{_id:0,host:'192.168.1.112:27897',arbiterOnly:true}}}

rs.initiate(cfg);
  • 副本集二

配置与副本集一样,命令执行如下:

cfg={_id:"shard002",members:{{_id:0,host:'192.168.1.111:27899'},{_id:0,host:'192.168.1.112:27899'},{_id:0,host:'192.168.1.112:27899'}}}

rs.initiate(cfg);
  • 混合使用

    1. 前置: M-S-S 的副本集以及M-S-A的副本集

    2. 新增一个副本集, 为config服务, 配置中添加节点并添加变量启动

    configsvr=true
    
    1. 新增路由服务器(只需要logpath,不需要dbpath), mongos -f ..启动
    configdb=configrs/192.168.1.111:28102,192.168.1.112:28102,192.168.1.113:28102
    
    1. 目前有了一组配置服务器, 一组路由服务器, 两组副本集服务器

      • 关联路由/shard: sh.addShard("shard001/192.168.1.111:27897") 以及 sh.addShard("shard002/192.168.1.111:27899")

      • 启用切片: use dbName sh.enableSharding("dbNzame")

      • sh.shardCollections("dbName.collectionName",{"name","hashed"})

      • 分片的服务器需要使用--shardsvr=true 所以需要在数据副本集的cfg中添加shardsvr=true

MongoDB的适用场景和不适用场景

适用于:

  • 实时插入, 更新和查询.
  • 数据缓存, mongoDB的索引会同步到内存, 数据存储在磁盘中
  • 大量数据存储,数据粒度较大, 数量较多
  • 高伸缩性场景
  • 对象或Json存储

不适用于:

  • 事务性系统, 银行会计系统等
  • BI 数据, BI数据库更合适
  • 复杂SQL查询

安装

参看官方文档

  • fork启动: mongod --dbpath=/opt/mongo/data/ --logpath=/opt/mongo/log/mongo.log --logappend --bind_ip=192.168.1.111 --fork

可以使用配置文件将参数配置到 mongo.cfg 类似properties文件的格式. 然后命令 mongod -f mongo.cfg 启动.

命令

  • use DBName; 转到数据库, 或者创建

  • db.DocName.insert({name:"docname"}) 插入数据

  • db.DocName.find() 或者 db.DocName.findOne() 查找

  • db.DocName.update({name:"docname"},{$set:{age:18}},true,true) 修改, 第三个参数为true则在查找不到记录的条件下新插入一条数据, 并设置属性列的值, 不影响其他属性; 第四个参数true表示批量

  • var p = db.doc.findOne(); db.doc.update(p,{name:"other"}) 会删除其他的列值

  • db.doc.remove({age:0}) 删除

  • db.doc.drop() 删除集合

  • db.dropDatabase() 删除库

  • show collections 查看集合

  • show dbs 查看数据库

  • db.doc.insert()db.doc.save() 前者不允许键值重复, 后者若键值重复则插入

  • 更新时候,第二个参数的模式

    • $set:设置
    • $unset:删除
    • $incr : 增加
    • $push: 数组增加元素
    • $pushAll: 批量增加数组元素
    • $addToSet: 有则不插入, 无则插入
    • $pop : 数组删除其中的元素, 1为删除最后一个, -1为删除第一个
    • $pull: 数组删除指定的值, $pullAll为批量操作
  • $each 迭代

  • runCommand() 函数, 实现组合操作

  • db.doc.find({条件},{指定键}) 查询模式

  • db.doc.find({age:{$gte:18,$lte:25}},{_id:0,name:1}) 范围查找,显式name列

    $lt, $lte,$gt , $gte,$ne, $in , $nin, $or

  • 支持正则表达式, find({name:/li/i})

  • $not

  • $all 和 index ; index 使用.0 .1 这样的方式表示

  • $size 数组大小

  • $slice 数组切割

  • limit(5) 限制显式条数

  • skip(10) 跳过条数

  • sort({age:1}) 排序, 1是正序, -1是逆序

  • hasNext() 结合 while 实现游标 , 注意: 游标默认10分钟会销毁

    var persons = db.person.find();
    while(persons.hasNext()){
        obj = person.next();
        print(obj.name);
    }
    
  • db.doc.find({$query:{name:"jim"},$snapshot:true}) 快照查询

    $query , $orderby, $maxscan , $min, $max, $hint , $explain , $snapshot

  • db.map.find({{gis:{$near:[70,180]}},{_id:0,gis:1}).limit(3) 查出离给定左表最近的是哪个点

  • db.map.find({gis:{$within:{$box:[[50,50],[100,100]}}},{_id:0,gis:i}) 查询所有在两个坐标为对角线内的所有点

  • db.map.find({gis:{$with:{$center:[[56,80],50]}}},{_id:0,gis:i}) 找出圆心为[56,80]半径50内的所有点

  • count() 查找计数

  • db.runCommand({distinct:"persons",key:"country"}).values persons中有多少个国家, 去重后的值

  • 分组

db.runCommand(
    {
        group:{
            ns:"集合名字",
            key:"分组键",
            initial:"初始化累加器",
            $reduce:"分解器"
            condition: "条件",
            finalize:"完成器"
        }
    }
);
  • db.createUser({user:"admin",pwd:"123",roles:[{role:"dbAdmin",db:"dbName"}]})

系统相关的需先使用 use admin 切换到系统库 比如: 查询用户db.system.users.find()

  • db.system.users.remove({use:"admin"}) 删除用户
  • db.runCommand({usersInfo:"admin",showPrivileges:true}) 查看用户权限
  • db.changeUserPassword("admin","123456") 修改密码
  • db.auth("admin","123456") 启用用户
  • rs.slaveOk() 设置允许在二级节点查询, 从节点上设置

mongodb 客户端使用

使用mongodb的官方驱动

  • 依赖包
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.10.2</version>
</dependency>
  • 代码
MongoClient mongo = new MongoClient("127.0.0.1", 27017);
DB db = new DB(mongo, "User");

DBCollection hiveUser = db.getCollection("hiveUser");
DBCursor cursor = hiveUser.find();
for (DBObject c : cursor) {
    System.out.println(c);
}

三方框架

  • 依赖包
<!-- https://mvnrepository.com/artifact/org.mongodb.morphia/morphia -->
<dependency>
    <groupId>org.mongodb.morphia</groupId>
    <artifactId>morphia</artifactId>
    <version>1.3.2</version>
</dependency>
  • 代码
Morphia morphia = new Morphia();
Datastore ds =morphia.createDatastore(new MongoClient("127.0.0.1", 27017),"hiveUser");
ds.save(new User("Test",3,19,0));
Query<User> query = ds.createQuery(User.class);
List<User> user = query.asList();
System.out.println(user.size());

Spring-data-mongodb

  • 依赖包
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
  • 配置
spring.data.mongodb.uri=mongodb://localhost/hiveUser

具体配置可以参考 org.springframework.boot.autoconfigure.mongo.MongoProperties

  • 代码
@Component
public class SpringDataMongoTest {

    @Autowired
    private MongoTemplate mongoTemplate;

    public void print(){
        Set<String> collections = mongoTemplate.getCollectionNames();
        System.out.println(collections);

        //查询
        Query query = new Query();
        List<User> list = mongoTemplate.find(query,User.class);
    }
}
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Document("hiveUser") //指定collection
public class User {
    private String name;
    private Integer id;
    private Integer age;
    private Integer sex;
}

注意: 操作实体上需要添加 @Document(collection="hiveUser") 才可以被查询.

posted @ 2019-04-29 12:24  罪恶斯巴克  阅读(309)  评论(0编辑  收藏  举报