簡單幾步,就可以配置好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中,然後根據條件擷取出來:
@AutowiredMongoTemplate mongoTemplate;@Testpublic 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”的記錄中,各種同姓的人員個數
@Testpublic 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}