spring-boot 配置mongoDB连接,保存、查找、统计操作

23 篇文章 0 订阅
12 篇文章 0 订阅

简单几步,就可以配置好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}






  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值