spring-boot 配置mongoDB串連,儲存、尋找、統計操作

來源:互聯網
上載者:User

簡單幾步,就可以配置好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}






相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.