官网指南地址 http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/
例子目录结构
pom.xml
<dependencies>mongodb.properties
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.0.3</version>
</dependency>
</dependencies>
mongodb.host=127.0.0.1
mongodb.port=
mongodb.replicaSet=
mongodb.connectionsPerHost=100
mongodb.threadsAllowedToBlockForConnectionMultiplier=5
mongodb.maxWaitTime=120000
mongodb.connectTimeout=60000
mongodb.socketTimeout=60000
mongodb.autoConnectRetry=true
mongodb连接配置
package mongodb.mongodb.test;
import java.util.ResourceBundle;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
/**
* mongodb连接配置工具类
* @author wbq
*
*/
public class MongoManager {
//MongoClient的实例代表数据库连接池,是线程安全的,可以被多线程共享,客户端在多线程条件下仅维持一个实例即可
//Mongo是非线程安全的,目前mongodb API中已经建议用MongoClient替代Mongo
private MongoClient mongoClient = null;
private static MongoManager instance = null;
private MongoManager(){
//属性文件读取参数信息
ResourceBundle bundle = ResourceBundle.getBundle("mongodb");
MongoClientOptions.Builder build = new MongoClientOptions.Builder();
//与目标数据库能够建立的最大connection数量,默认100
build.connectionsPerHost(Integer.valueOf(bundle.getString("mongodb.connectionsPerHost")));
build.threadsAllowedToBlockForConnectionMultiplier(Integer.valueOf(bundle.getString("mongodb.threadsAllowedToBlockForConnectionMultiplier")));
/*
* 一个线程访问数据库的时候,在成功获取到一个可用数据库连接之前的最长等待时间为2分钟
* 这里比较危险,如果超过maxWaitTime都没有获取到这个连接的话,该线程就会抛出Exception
* 故这里设置的maxWaitTime应该足够大,以免由于排队线程过多造成的数据库访问失败
*/
build.maxWaitTime(Integer.valueOf(bundle.getString("mongodb.maxWaitTime")));
//与数据库建立连接的timeout设置为1分钟
build.connectTimeout(Integer.valueOf(bundle.getString("mongodb.connectTimeout")));
build.socketTimeout(Integer.valueOf(bundle.getString("mongodb.socketTimeout")));
MongoClientOptions myOptions = build.build();
//数据库连接实例
mongoClient = new MongoClient("127.0.0.1", myOptions);
}
public static MongoManager getInstance(){
if(instance ==null){
instance = new MongoManager();
}
return instance;
}
public static MongoClient getMongoClient(){
return MongoManager.getInstance().mongoClient;
}
}
测试代码
package mongodb.mongodb.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bson.Document;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;
import static com.mongodb.client.model.Sorts.*;
import com.mongodb.client.model.BulkWriteOptions;
import com.mongodb.client.model.DeleteOneModel;
import com.mongodb.client.model.InsertOneModel;
import com.mongodb.client.model.ReplaceOneModel;
import com.mongodb.client.model.UpdateOneModel;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
public class MongoTest {
private MongoClient client = MongoManager.getMongoClient();
private MongoDatabase md = client.getDatabase("local");
private MongoCollection<Document> coll = null;
//创建集合
@Before
public void create(){
md.createCollection("test");
coll = md.getCollection("test");
}
@Test
public void run(){
add();
query();
update();
testDel();
bulk();
}
//添加测试
public void add(){
//添加单条记录
Document doc = new Document("name","MongoDB").append("type", "database").append("count", 1)
.append("info", new Document("x", 203).append("y", 102));
coll.insertOne(doc);
//添加多条记录
List<Document> list = new ArrayList<Document>();
for(int i= 0 ;i< 100 ;i++){
list.add(new Document("i", i));
}
coll.insertMany(list);
}
//查询
public void query(){
//查询第一条
Document doc = coll.find().first();
System.out.println(doc.toJson());
//查询所有
try(MongoCursor<Document> cursor = coll.find().iterator()){
while(cursor.hasNext()){
System.out.println(cursor.next().toJson());
}
}
//过滤查询 单条
doc = coll.find(eq("i", 71)).first();
System.out.println(doc.toJson());
//过滤查询 多条
Block<Document> printBlock = new Block<Document>(){
@Override
public void apply(Document t) {
System.out.println("i>50 "+t.toJson());
}
};
coll.find(gt("i",50)).forEach(printBlock);
//排除 降序 第一条数据
doc = coll.find(exists("i")).sort(descending("i")).first();
System.out.println("sort: " + doc.toJson());
doc = coll.find().projection(excludeId()).first();
System.out.println("excludeId: "+doc.toJson());
}
//更新测试
public void update(){
//更新单独记录
coll.updateOne(eq("i","10"), new Document("$set",new Document("i", 110)));
//跟新多条记录 $set 设置为指定值 $inc 原子性操作 将原来的加上 新值
UpdateResult updateResult = coll.updateMany(lt("i", 100),new Document("$inc",new Document("i",100)));
System.out.println("ModifiedCount:" + updateResult.getModifiedCount());
}
//删除测试
public void testDel(){
//删除单个 找到符合条件的第一个 删除
coll.deleteOne(eq("i",110));
//删除多个 只要符合条件就全部删除
DeleteResult deleteResult = coll.deleteMany(gte("i",100));
System.out.println("DeletedCount:"+deleteResult.getDeletedCount());
}
//批量操作
public void bulk(){
//有序
coll.bulkWrite(
Arrays.asList(new InsertOneModel<Document>(new Document("_id", 1)),
new InsertOneModel<Document>(new Document("_id", 2)),
new InsertOneModel<Document>(new Document("_id", 3)),
new UpdateOneModel<Document>(new Document("_id", 1),new Document("$set", new Document("x", 2))),
new DeleteOneModel<Document>(new Document("_id",2)),
new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x",4))));
//无序
coll.bulkWrite(
Arrays.asList(new InsertOneModel<Document>(new Document("_id", 4)),
new InsertOneModel<Document>(new Document("_id", 5)),
new InsertOneModel<Document>(new Document("_id", 6)),
new UpdateOneModel<Document>(new Document("_id", 4),
new Document("$set", new Document("x", 2))),
new DeleteOneModel<Document>(new Document("_id", 5)),
new ReplaceOneModel<Document>(new Document("_id", 6),
new Document("_id", 6).append("x", 4))),
new BulkWriteOptions().ordered(false));
}
@After
public void queryAll(){
System.out.println(coll.count());
FindIterable<Document> docs = coll.find();
MongoCursor<Document> cur = docs.iterator();
while(cur.hasNext()){
System.out.println(cur.next());
}
//删除集合
coll.drop();
}
}