MongoDB的简单介绍
程序员文章站
2022-04-30 22:17:12
...
MongoDB的安装和启动就不介绍了;
创建maven工程,引入依赖
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.4.1</version>
</dependency>
</dependencies>
创建实体类对象StudentDao
package cn.liuzhengwei.demo;
import org.bson.Document;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
/**
* 数据访问层
* @author Administrator
*/
public class StudentDao {
public void save(String name,String sex,double age,String address){
MongoDatabase database = MongoManager.getDatabase();
MongoCollection<Document> collection = database.getCollection("student2");
Document docment=new Document();
docment.put("name", name);
docment.put("sex", sex);
docment.put("age", age);
docment.put("address", address);
collection.insertOne(docment);
}
}
MongoClient 被设计为线程安全的类,也就是我们在使用该类时不需要考虑并发的情况,这样我们可以考虑把MongoClient 做成一个静态变量,为所有线程公用,不必每次都销毁。这样可以极大提高执行效率。实际上,这是MongoDB提供的内置的连接池来实现的。
我们要创建一个“管理类”,相当于我们原来的BaseDao
package cn.liuzhengwei.demo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientOptions.Builder;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoDatabase;
public class MongoManager {
private static MongoClient mongoClient=null;
//对mongoClient初始化
private static void init(){
//连接池选项
Builder builder = new MongoClientOptions.Builder();//选项构建者
builder.connectTimeout(5000);//设置连接超时时间
builder.socketTimeout(5000);//读取数据的超时时间
builder.connectionsPerHost(30);//每个地址最大请求数
builder.writeConcern(WriteConcern.NORMAL);//写入策略,仅抛出网络异常
MongoClientOptions options = builder.build();
mongoClient=new MongoClient("127.0.0.1",options);
}
public static MongoDatabase getDatabase(){
if(mongoClient==null){
init();
}
return mongoClient.getDatabase(数据库名);
}
}
下面是写入策略。
WriteConcern.NONE:没有异常抛出
WriteConcern.NORMAL:仅抛出网络错误异常,没有服务器错误异常
WriteConcern.SAFE:抛出网络错误异常、服务器错误异常;并等待服务器完成写操作。
WriteConcern.MAJORITY: 抛出网络错误异常、服务器错误异常;并等待一个主服务器完成写操作。
WriteConcern.FSYNC_SAFE: 抛出网络错误异常、服务器错误异常;写操作等待服务器将数据刷新到磁盘。
WriteConcern.JOURNAL_SAFE:抛出网络错误异常、服务器错误异常;写操作等待服务器提交到磁盘的日志文件。
WriteConcern.REPLICAS_SAFE:抛出网络错误异常、服务器错误异常;等待至少2台服务器完成写操作。
编写测试类 插入2000条数据
package cn.liuzhengwei.demo;
import java.util.Date;
public class TestPool {
public static void main(String[] args) {
long startTime = new Date().getTime();//开始时间
StudentDao studentDao=new StudentDao();
for(int i=0;i<20000;i++){
studentDao.save("测试"+i, "男", 25.0, "测试地址"+i);
}
long endTime = new Date().getTime();//完成时间
System.out.println("完成时间:"+(endTime-startTime)+"毫秒");
}
}
各种查询方式汇总
package com.liuzhengwei.demo;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.regex.Pattern;
public class Demo {
/**
* 查询全部记录
*/
@Test
public void demotest(){
MongoClient client=new MongoClient();//创建连接对象
MongoDatabase database = client.getDatabase("db");//获取数据库
MongoCollection<Document> collection = database.getCollection("student");//获取集合
FindIterable<Document> list = collection.find();//获取文档集合
for( Document doc: list){//遍历集合中的文档输出数据
System.out.println("name:"+ doc.getString("name") );
System.out.println("sex:"+ doc.getString("sex") );
System.out.println("age:"+ doc.getDouble("age") );//默认为浮点型
System.out.println("address:"+ doc.getString("address") );
System.out.println("--------------------------");
}
}
/**
* 条件查询
*/
@Test
public void demo2(){
MongoClient client=new MongoClient();//创建连接对象
MongoDatabase database = client.getDatabase("db");//获取数据库
MongoCollection<Document> collection = database.getCollection("student");//获取集合
//构建查询条件
BasicDBObject bson = new BasicDBObject ("name","白龙马");
FindIterable <Document> documents = collection.find (bson);
for (Document doc : documents) {
System.out.println("name:"+ doc.getString("name") );
System.out.println("sex:"+ doc.getString("sex") );
System.out.println("age:"+ doc.getDouble("age") );//默认为浮点型
System.out.println("address:"+ doc.getString("address") );
System.out.println("--------------------------");
}
}
/**
* 构建模糊查询条件是通过正则表达式的方式来实现的
* 完全匹配Pattern pattern = Pattern.compile("^name$");
* 右匹配Pattern pattern = Pattern.compile("^.*name$");
* 左匹配Pattern pattern = Pattern.compile("^name.*$");
* 模糊匹配Pattern pattern = Pattern.compile("^.*name.*$");
*/
@Test
public void demo3(){
MongoClient client=new MongoClient();//创建连接对象
MongoDatabase database = client.getDatabase("db");//获取数据库
MongoCollection<Document> collection = database.getCollection("student");//获取集合
//构建模糊查询条件
//Pattern pattern = Pattern.compile ("^白龙马$");
Pattern pattern = Pattern.compile ("^.*白.*$");
BasicDBObject bson = new BasicDBObject ("name", pattern);
FindIterable <Document> list = collection.find (bson);
for (Document doc : list) {
System.out.println("name:"+ doc.getString("name") );
System.out.println("sex:"+ doc.getString("sex") );
System.out.println("age:"+ doc.getDouble("age") );//默认为浮点型
System.out.println("address:"+ doc.getString("address") );
System.out.println("--------------------------");
}
}
/**
* 大于小于
* 条件嵌套
*/
@Test
public void demo4(){
MongoClient client=new MongoClient();//创建连接对象
MongoDatabase database = client.getDatabase("db");//获取数据库
MongoCollection<Document> collection = database.getCollection("student");//获取集合
BasicDBObject $lt = new BasicDBObject ("$lte", 20);//小于 gt大于 gte大于等于 lte小于等于
BasicDBObject bson = new BasicDBObject ("age", $lt);
FindIterable <Document> list = collection.find (bson);
for (Document doc : list) {
System.out.println("name:"+ doc.getString("name") );
System.out.println("sex:"+ doc.getString("sex") );
System.out.println("age:"+ doc.getDouble("age") );//默认为浮点型
System.out.println("address:"+ doc.getString("address") );
System.out.println("--------------------------");
}
}
/**
* 条件连接--并且
*
*/
@Test
public void demo5(){
MongoClient client = new MongoClient ();
MongoDatabase database = client.getDatabase ("db");
MongoCollection <Document> collection = database.getCollection ("student");
BasicDBObject gte = new BasicDBObject ("age", new BasicDBObject ("$gte",20));
BasicDBObject lte = new BasicDBObject ("age", new BasicDBObject("$lt",30));
BasicDBObject bson = new BasicDBObject ("$and", Arrays.asList (gte, lte));
FindIterable <Document> list = collection.find (bson);
for (Document doc : list) {
System.out.println("name:"+ doc.getString("name") );
System.out.println("sex:"+ doc.getString("sex") );
System.out.println("age:"+ doc.getDouble("age") );//默认为浮点型
System.out.println("address:"+ doc.getString("address") );
System.out.println("--------------------------");
}
}
/**
* 条件连接--或者
*
*/
@Test
public void demo6(){
System.out.println ("aaaaaaaaa");
MongoClient client = new MongoClient ();
MongoDatabase database = client.getDatabase ("db");
MongoCollection <Document> collection = database.getCollection ("student");
BasicDBObject bson1 = new BasicDBObject ("age", new BasicDBObject ("$lte",20));
BasicDBObject bson2 = new BasicDBObject ("sex", "女");
BasicDBObject bson = new BasicDBObject ("$or", Arrays.asList (bson1, bson2));
FindIterable <Document> list = collection.find (bson);
for (Document doc : list) {
System.out.println("name:"+ doc.getString("name") );
System.out.println("sex:"+ doc.getString("sex") );
System.out.println("age:"+ doc.getDouble("age") );//默认为浮点型
System.out.println("address:"+ doc.getString("address") );
System.out.println("--------------------------");
}
}
/**
* 增
* insertOne方法来插入文档 updateMany方法用于修改符合条件的所有记录
updateOne方法用于修改符合条件的第一条记录
*/
@Test
public void demo7(){
MongoClient client = new MongoClient ();
MongoDatabase database = client.getDatabase ("db");
MongoCollection <Document> collection = database.getCollection ("student");
//创建集合封装对象
HashMap <String, Object> map = new HashMap <> ();
map.put ("name","铁扇公主");
map.put ("age",23.0);
map.put ("sex","女");
map.put ("address","牛头山");
Document document = new Document (map);
collection.insertOne (document);//插入一条数据
//collection.insertMany(documents);//一次性插入多条文档
}
/**
* 删除文档
*
*/
@Test
public void demo8(){
MongoClient client = new MongoClient ();
MongoDatabase database = client.getDatabase ("db");
MongoCollection <Document> collection = database.getCollection ("student");
BasicDBObject bson = new BasicDBObject ("name", "铁扇公主");
collection.deleteOne (bson);
}
/**
* 修改
*
*
*/
@Test
public void demo9(){
MongoClient client = new MongoClient ();
MongoDatabase database = client.getDatabase ("db");
MongoCollection <Document> collection = database.getCollection ("student");
BasicDBObject bson = new BasicDBObject ("name", "铁扇公主");
BasicDBObject bson2 = new BasicDBObject ("$set", new BasicDBObject ("address", "南山"));
collection.updateMany (bson, bson2);
}
}
下一篇: Git常用命令整理