简单几步,就可以配置好mongoDB的连接,然后使用MongoTemplate操作数据:
1、引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2、application.yml中配置连接信息:
spring:
data:
mongodb:
uri: mongodb://192.168.0.9:27017/test
其中:test是db的名字。
3、创建一个实体类:
package com.xjj.entity;
import java.util.Date;
public class Person {
private int id;
private String firstName;
private String lastName;
private Date birthDate;
private char sex; //'M', 'F'
private String phoneNo;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
4、把实体类存入mongoDB中,然后根据条件获取出来:
@Autowired
MongoTemplate mongoTemplate;
@Test
public void mongoSaveGetTest() throws JsonProcessingException {
String dbName = mongoTemplate.getDb().getName();
logger.info("db name: {}", dbName);
assertThat(dbName, is("test"));
for(int i=3;i<=25;i++){
Person p = personDAO.getPersonById(i);
if(p!=null){
mongoTemplate.save(p);
}
}
Criteria c = new Criteria();
c.and("id").is(3);
Person gotP = mongoTemplate.findOne(Query.query(c), Person.class);
logger.debug("p={}", objectMapper.writeValueAsString(gotP));
assertThat(gotP.getFirstName(), equalTo("七"));
Set<String> collectionNames = mongoTemplate.getDb().getCollectionNames();
logger.info("colection names: {}", collectionNames);
assertThat(collectionNames, hasItem("person"));
}
5、统计:统计性别为“F”的记录中,各种同姓的人员个数
@Test
public void mongoAggregationTest() throws JsonProcessingException{
Criteria c = new Criteria();
c.and("sex").is("F");
Aggregation aggr = Aggregation.newAggregation(
Aggregation.match(c),
Aggregation.group("lastName").count().as("count")
);
AggregationResults<BasicDBObject> aggrResult = mongoTemplate.aggregate(aggr, "person", BasicDBObject.class);
if(!aggrResult.getMappedResults().isEmpty()){
for(BasicDBObject obj : aggrResult.getMappedResults()){
logger.info("count by first name: {}", objectMapper.writeValueAsString(obj));
}
}
}
统计结果:
2016-10-27 18:02:11,911:INFO main (MySpringBootApplicationTests.java:111) - count by first name: {"_id":"田","count":1}
2016-10-27 18:02:11,912:INFO main (MySpringBootApplicationTests.java:111) - count by first name: {"_id":"李","count":19}