MongoDB
•MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。
•在高负载的情况下,添加更多的节点,可以保证服务器性能。
•MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案。
•MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。
{
“id”:1,
“author”:”Jane”,
“blogposts”:{
“tile”:”MyFirstPost”, “comment”:{
“by”:”Ada”,
”text”:”Good post”
}
}
}
特点
- 提供了一个面向文档存储,操作起来比较简单和容易
- 可以设置任何属性的索引来实现更快的排序
- 具有较好的水平可扩展性
- 支持丰富的查询表达式,可轻易查询文档中内嵌的对象及数组
- 可以实现替换完成的文档(数据)或者一些指定的数据字段
- MongoDB中的Map/Reduce主要是用来对数据进行批量处理和聚合操作
- 支持各种编程语言:RUBY,PYTHON,JAVA,C++,PHP,C#等语言
- MongoDB安装简单
数据库
•一个mongodb中可以建立多个数据库。
•MongoDB的默认数据库为"db",该数据库存储在data目录中。
•MongoDB的单个实例可以容纳多个独立的数据库,每一个都有自己的集合和权限,不同的数据库也放置在不同的文件中。
文档
文档是一个键值(key-value)对(即BSON)。MongoDB 的文档不需要设置相同的字段,并且相同的字段不需要相同的数据类型,这与关系型数据库有很大的区别,也是 MongoDB 非常突出的特点。
集合
•集合就是 MongoDB 文档组,类似于 RDBMS (关系数据库管理系统:Relational Database Management System)中的表格。
•集合存在于数据库中,集合没有固定的结构,这意味着你在对集合可以插入不同格式和类型的数据,但通常情况下我们插入集合的数据都会有一定的关联性。
比如,我们可以将以下不同数据结构的文档插入到集合中:
Mongo与RDBMS的术语对比
数据类型
安装mongodb
mongo -version 查看mongo版本
sudo service mongod start #启动mongo
sudo service mongod stop #关闭mongo
sudo service mongod restart #重启mongo
Shell
show dbs #显示数据库列表
show collections #显示当前数据库中的集合(类似关系数据库中的表table)
show users #显示所有用户
use yourDB #切换当前数据库至yourDB,如果数据库不存在,则创建数据库
#MongoDB没有单独创建集合名的shell命令,在插入数据的时候,MongoDB会自动创建对应的集合。
db.COLLECTION_NAME.insert(document)
#e.g.
db.student.insert(
{
'name': 'lisi',
'score': {
'English': 55,
'Math': 100,
'Computer': 88
}
}
);
#查询方法
db.COLLECTION_NAME.find(条件,返回结果)
#e.g.
db.student.find({name:"zhangsan"},{"_id":0,"score":1});#0表示不返回,1表示返回
# 查询worker集合中name属性是"majinqiao"的数据
# pretty函数 ,以格式化的方式显示查询结果
db.worker.find({name:"majinqiao"}).pretty()
# or查询 name = "majinqiao" or score = 54
db.worker.find({$or:[{name:"majinqiao"},{score:54}]}).pretty()
# or查询 age < 30 or age > 50
db.worker.find({$or:[{age:{$lt:30}},{age:{$gt:50}}]})
# or查询 age <= 30 or age => 50
db.worker.find({$or:[{age:{$lte:30}},{age:{$gte:50}}]})
# and查询 age != 30 and name != 'chengya'
db.worker.find({age:{$ne:30},age:{$ne:50}})
# and查询,name = "majinqiao" and age = 36
db.worker.find({name:"majinqiao",age:36}).pretty()
# 查找name字段为字符串的数据
db.worker.find({name:{$type:"string"}})
# 限制查询结果条数为2条
db.worker.find({name:"zhangjian"}).limit(2)
# province字段正序排列,city_age字段倒序排列
db.city.find().sort({province:1,city_age:-1})
# 当limit,skip,sort同时出现时,逻辑顺序为sort,skip,limit
db.worker.find({name:"zhangjian"}).limit(2).skip(1).sort({score:1})
# 查询city集合中存在history字段,且history的值是null的数据
db.city.find({history:{$in:[null],$exists:true}})
# select _id,city_name as cityName from city where city_name = 'jingzhou' and city_age >= 10
# _id 是默认查询的,如果想不返回这个字段, _id:0 即可
db.city.find({city_name:"jingzhou",city_age:{$gte:10}},{cityName:"$city_name"})
Java
导入依赖项
导入依赖或引入jar包
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.11</version>
</dependency>
连接数据库和集合
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("test"); //数据库
MongoCollection<Document> student = database.getCollection("student"); //集合
插入数据
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> student = database.getCollection("student");
Document score = new Document("English",45).append("Math",89).append("Computer",100);
Document doc = new Document("name","scofield").append("score",score);
student.insertOne(doc);
}
查询数据
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> student = database.getCollection("student");
FindIterable<Document> iterable = student.find(new BasicDBObject("name","scofield"));
for(Document doc : iterable){
System.out.println(doc.get("score"));
}
}
旧版API
连接数据库
import com.mongodb.MongoClient;
……//这里省略其他需要导入的包
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
创建集合
可以使用com.mongodb.DB类中的createCollection()来创建集合
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
DBCollection coll = db.createCollection("mycol");
System.out.println("Collection created successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
插入文档
可以使用com.mongodb.DBCollection类的 insert() 方法来插入一个文档
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
DBCollection coll = db.getCollection("mycol");
System.out.println("Collection mycol selected successfully");
BasicDBObject doc = new BasicDBObject("title", "MongoDB").
append("description", "database").
append("likes", 100).
append("url", "http://www.w3cschool.cc/mongodb/").
append("by", "w3cschool.cc");
coll.insert(doc);
System.out.println("Document inserted successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}