一. 环境搭建
二. 原生java驱动Document的操作测
三. 原生java驱动pojo的操作测试
四. spring pojo的操作测试
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-mongodbartifactId>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<scope>testscope>
dependency>
在mongo-template-CRUD项目下的:MongoTemplateTest.java(后面有提供github地址)
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Updates.*;
/**
* 原生java驱动Document的操作测
*
* @author dylan
* @date 2018年4月13日下午11:43:17
*/
public class MongoTemplateTest {
private static final Logger log = LoggerFactory.getLogger(MongoTemplateTest.class);
private MongoDatabase db;
private MongoCollection doc;
private MongoClient client;
@Before
public void init() {
client = new MongoClient("127.0.0.1", 27017);
db = client.getDatabase("test");
doc = db.getCollection("users");
}
/**
* 测试插入数据
*/
@Test
public void testInsert() {
Document doc1 = new Document();
doc1.append("username", "tom");
doc1.append("contry", "Englan");
doc1.append("age", 18);
doc1.append("lenght", 1.77f);
doc1.append("salary", new BigDecimal("6585.23"));
Map address1 = new HashMap();
address1.put("aCode", "0000");
address1.put("add", "xxx000");
doc1.append("address", address1);
Map favorites1 = new HashMap();
favorites1.put("movies", Arrays.asList("aa", "bb"));
favorites1.put("cities", Arrays.asList("广州", "深圳"));
doc1.append("favorites", favorites1);
Document doc2 = new Document();
doc2.append("username", "tony");
doc2.append("contry", "USA");
doc2.append("age", 28);
doc2.append("lenght", 1.77f);
doc2.append("salary", new BigDecimal("6585.23"));
Map address2 = new HashMap();
address2.put("aCode", "0000");
address2.put("add", "xxx000");
doc2.append("address", address2);
Map favorites2 = new HashMap();
favorites2.put("movies", Arrays.asList("cc", "dd"));
favorites2.put("cities", Arrays.asList("南宁", "衡阳"));
doc2.append("favorites", favorites2);
doc.insertMany(Arrays.asList(doc1, doc2));
}
/**
* 删除测试
*/
@Test
public void testDelete() {
// delete from users where username = 'iuv'
DeleteResult deleteMany = doc.deleteMany(Filters.eq("username", "iuv"));
log.info("删除的行数为:{}", deleteMany.getDeletedCount());
// delete from users where age >8 and age <25
DeleteResult deleteMany2 = doc.deleteMany(and(gt("age", 8), lt("age", 25)));
log.info("删除的行数为:{}", deleteMany2.getDeletedCount());
}
/**
* 更新测试
*/
@Test
public void testUpdate() {
// update users set age = 6 where username = 'tom'
UpdateResult updateNum = doc.updateMany(eq("username", "tom"), new Document("$set", new Document("age", 6)));
log.info("更新的行数为:{}", updateNum.getModifiedCount());
// update users set favorites.movies add "蜘蛛侠","钢铁侠" where
// favorites.cities has "深圳"
UpdateResult updateNum2 = doc.updateMany(eq("favorites.cities", "深圳"),
addEachToSet("favorites.movies", Arrays.asList("蜘蛛侠", "钢铁侠")));
log.info("更新的行数为:{}", updateNum2.getModifiedCount());
}
/**
* 查询测试
*/
@Test
public void testFind() {
final List ret = new ArrayList<>();
Block printBlock = new Block() {
@Override
public void apply(Document t) {
log.info("{}", t.toJson());
ret.add(t);
}
};
// select * from users where favorites.cities has "深圳"、"广州"
FindIterable find = doc.find(all("favorites.cities", Arrays.asList("深圳", "广州")));
find.forEach(printBlock);
log.info(String.valueOf(ret.size()));
ret.removeAll(ret);// 将集合清空
// select * from users where username like '%om%' and (contry=Englan or
// contry=USA)
String regexStr = ".*om.*";
Bson regex = regex("username", regexStr);
Bson or = or(eq("contry", "Englan"), eq("contry", "USA"));
FindIterable find2 = doc.find(and(regex, or));
find2.forEach(printBlock);
log.info(String.valueOf(ret.size()));
}
}
在mongo-template-CRUD项目下的:MongoTemplateTest2.java(后面有提供github地址)
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.conversions.Bson;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dylan.pojo.Address;
import com.dylan.pojo.Favorites;
import com.dylan.pojo.User;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Updates.*;
/**
* 原生java驱动pojo的操作测试
*
* @author dylan
* @date 2018年4月13日下午11:43:55
*/
public class MongoTemplateTest2 {
private static final Logger log = LoggerFactory.getLogger(MongoTemplateTest2.class);
private MongoDatabase db;
private MongoCollection doc;
private MongoClient client;
@Before
public void init() {
// 编解码器的list
List codecRegisties = new ArrayList();
// 将默认的编解码器加入到list
codecRegisties.add(MongoClient.getDefaultCodecRegistry());
// 生成一个pojo的编解码器注册中心
CodecRegistry pojoProviders = CodecRegistries
.fromProviders(PojoCodecProvider.builder().automatic(true).build());
codecRegisties.add(pojoProviders);
// 通过编解码器list生成编解码器注册中心
CodecRegistry register = CodecRegistries.fromRegistries(codecRegisties);
// 把编解码器注册中心放到MongoClientOptions中去(MongoClientOption可以看成是封装了配置文件的类)
MongoClientOptions build = MongoClientOptions.builder().codecRegistry(register).build();
// 创建服务器连接
ServerAddress serverAddress = new ServerAddress("127.0.0.1", 27017);
client = new MongoClient(serverAddress, build);
db = client.getDatabase("test");
doc = db.getCollection("users", User.class);
}
/**
* 测试插入数据
*/
@Test
public void testInsert() {
User user1 = new User();
user1.setUsername("dylan1");
user1.setAge(18);
user1.setCountry("中国");
user1.setLenght(1.70f);
user1.setSalary(new BigDecimal(10000));
Address address1 = new Address();
address1.setaCode("0000");
address1.setAdd("XXXXXXXXX");
user1.setAddress(address1);
Favorites favorites1 = new Favorites();
favorites1.setCites(Arrays.asList("广州", "深圳"));
favorites1.setMovies(Arrays.asList("西游记", "水浒传"));
user1.setFavorites(favorites1);
User user2 = new User();
user2.setUsername("dylan2");
user2.setAge(18);
user2.setCountry("美国");
user2.setLenght(1.70f);
user2.setSalary(new BigDecimal(10000));
Address address2 = new Address();
address2.setaCode("1111");
address2.setAdd("YYYYYYYYYY");
user2.setAddress(address2);
Favorites favorites2 = new Favorites();
favorites2.setCites(Arrays.asList("南宁", "衡阳"));
favorites2.setMovies(Arrays.asList("红楼梦", "三国演义"));
user2.setFavorites(favorites2);
doc.insertMany(Arrays.asList(user1, user2));// 插入方式与document调用同一个方法
}
/**
* 删除测试 -----与Document的方式一摸一样,代码完全不需要修改
*/
@Test
public void testDelete() {
// delete from users where username = 'dylan1'
DeleteResult deleteMany = doc.deleteMany(Filters.eq("username", "dylan1"));
log.info("删除的行数为:{}", deleteMany.getDeletedCount());
// delete from users where age >8 and age <25
DeleteResult deleteMany2 = doc.deleteMany(and(gt("age", 8), lt("age", 25)));
log.info("删除的行数为:{}", deleteMany2.getDeletedCount());
}
/**
* 更新测试 -----与Document的方式一摸一样,代码完全不需要修改
*/
@Test
public void testUpdate() {
// update users set age = 10 where username = 'tom'
UpdateResult updateNum = doc.updateMany(eq("username", "tom"), new Document("$set", new Document("age", 10)));
log.info("更新的行数为:{}", updateNum.getModifiedCount());
// update users set favorites.movies add "蜘蛛侠","钢铁侠" where
// favorites.cities has "深圳"
UpdateResult updateNum2 = doc.updateMany(eq("favorites.cities", "深圳"),
addEachToSet("favorites.movies", Arrays.asList("蜘蛛侠", "钢铁侠")));
log.info("更新的行数为:{}", updateNum2.getModifiedCount());
}
/**
* 查询测试-------将Document修改为User即可,其它不需要修改
*/
@Test
public void testFind() {
final List ret = new ArrayList<>();
Block printBlock = new Block() {
@Override
public void apply(User user) {
log.info("{}", user.toString());
ret.add(user);
}
};
// select * from users where favorites.cities has "深圳"、"广州"
FindIterable find = doc.find(all("favorites.cities", Arrays.asList("深圳", "广州")));
find.forEach(printBlock);
log.info(String.valueOf(ret.size()));
ret.removeAll(ret);// 将集合清空
// select * from users where username like '%om%' and (contry=Englan or
// contry=USA)
String regexStr = ".*om.*";
Bson regex = regex("username", regexStr);
Bson or = or(eq("contry", "Englan"), eq("contry", "USA"));
FindIterable find2 = doc.find(and(regex, or));
find2.forEach(printBlock);
log.info(String.valueOf(ret.size()));
}
}
1、先引用spring操作mongodb的jar包,这是使用的springboot的项目
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-mongodbartifactId>
<exclusions>
<exclusion>
<groupId>org.mongodbgroupId>
<artifactId>mongo-java-driverartifactId>
exclusion>
exclusions>
dependency>
2、在application.properties中添加mongodb的连接(这里使用的url连接,minPoolSize是最小连接数,maxPoolSize是最大连接数,socketTimeoutMS是连接超时时间,还有别的一些参数这里不详细讲)
spring.data.mongodb.uri=mongodb://root:123456@127.0.0.1:27017/test?maxPoolSize=100;minPoolSize=10;socketTimeoutMS=20000
注:这里只是简单的说了一下springboot集成mongoDB,建议自行百度:springboot 集成mongodb
3、测试的代码
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.test.context.junit4.SpringRunner;
import com.dylan.mongo.pojo.Address;
import com.dylan.mongo.pojo.Favorites;
import com.dylan.mongo.pojo.User;
import com.mongodb.WriteResult;
/**
* spring pojo的操作测试
*
* @author dylan
* @date 2018年4月13日下午11:43:55
*/
@RunWith(SpringRunner.class)
@SpringBootTest // springboot项目的加载方式
// @ContextConfiguration("classpath:applicationContext.xml") //spring加载配置的方式
public class MongoTemplateSpring {
private static final Logger log = LoggerFactory.getLogger(MongoTemplateSpring.class);
@Resource
private MongoOperations tempelate;
/**
* 测试插入数据
*/
@Test
public void testInsert() {
User user1 = new User();
user1.setUsername("tom");
user1.setAge(18);
user1.setCountry("中国");
user1.setLenght(1.70f);
user1.setSalary(new BigDecimal(10000));
Address address1 = new Address();
address1.setaCode("0000");
address1.setAdd("XXXXXXXXX");
user1.setAddress(address1);
Favorites favorites1 = new Favorites();
favorites1.setCities(Arrays.asList("广州", "深圳"));
favorites1.setMovies(Arrays.asList("西游记", "水浒传"));
user1.setFavorites(favorites1);
User user2 = new User();
user2.setUsername("tom");
user2.setAge(18);
user2.setCountry("美国");
user2.setLenght(1.70f);
user2.setSalary(new BigDecimal(10000));
Address address2 = new Address();
address2.setaCode("1111");
address2.setAdd("YYYYYYYYYY");
user2.setAddress(address2);
Favorites favorites2 = new Favorites();
favorites2.setCities(Arrays.asList("南宁", "衡阳"));
favorites2.setMovies(Arrays.asList("红楼梦", "三国演义"));
user2.setFavorites(favorites2);
tempelate.insertAll(Arrays.asList(user1, user2));
}
/**
* 删除测试
*/
@Test
public void testDelete() {
// delete from users where username = 'dylan1'
WriteResult remove = tempelate.remove(Query.query(Criteria.where("username").is("tony")), User.class);
log.info("remove.getN()====={}", remove.getN());
// delete from users where age >8 and age <25
WriteResult remove2 = tempelate.remove(
Query.query(new Criteria().andOperator(Criteria.where("age").gt(8), Criteria.where("age").lt(25))),
User.class);
log.info("remove2.getN()====={}", remove2.getN());
}
/**
* 更新测试
*/
@Test
public void testUpdate() {
// update users set age = 10 where username = 'tom'
WriteResult updateResult = tempelate.updateMulti(Query.query(Criteria.where("username").is("tom")),
Update.update("age", 10), User.class);
log.info("updateResult=:{}", updateResult);
log.info("updateResult.getN()={}", updateResult.getN());
// update users set favorites.movies add "蜘蛛侠","钢铁侠" where
// favorites.cities has "深圳"
Query query = Query.query(Criteria.where("favorites.cities").is("深圳"));
Update update = new Update().addToSet("favorites.movies").each("钢铁侠", "蜘蛛侠");
WriteResult updateResult2 = tempelate.updateMulti(query, update, User.class);
log.info("updateResult2={}", updateResult2);
log.info("updateResult2.getN()={}", updateResult2.getN());
}
/**
* 查询测试-------将Document修改为User即可,其它不需要修改
*/
@Test
public void testFind() {
// select * from users where favorites.cities has "深圳"、"广州"
List find = tempelate.find(Query.query(Criteria.where("favorites.cities").all(Arrays.asList("深圳", "广州"))),
User.class);
log.info("find.size()={}", find.size());
// select * from users where username like '%om%' and (contry=Englan or
// contry=USA)
String regexStr = ".*om.*";
Criteria regex = Criteria.where("username").regex(regexStr);
Criteria or1 = Criteria.where("country").is("Englan");
Criteria or2 = Criteria.where("country").is("USA");
Criteria or = new Criteria().orOperator(or1, or2);
Query query = Query.query(new Criteria().andOperator(regex, or));
List find2 = tempelate.find(query, User.class);
for (User user : find2) {
log.info("user==={}", user.toString());
}
}
}
没怎么写博客,写的不好或者有错误的地方大家可以指出来,附上我的github地址:源代码地址,在mongo-template-CRUD项目下