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
集群模式
步骤
- 主从配置(主节点挂掉就不可用)
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);
混合使用
configsvr=true
- 新增路由服务器(只需要logpath,不需要dbpath),
mongos -f ..
启动
configdb=configrs/192.168.1.111:28102,192.168.1.112:28102,192.168.1.113:28102
- 新增路由服务器(只需要logpath,不需要dbpath),
MongoDB的适用场景和不适用场景
适用于:
不适用于:
安装
参看官方文档
- 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()
前者不允许键值重复, 后者若键值重复则插入更新时候,第二个参数的模式
$each
迭代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")
才可以被查询.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。