1. 程式人生 > >Spring Boot 整合MongoDB

Spring Boot 整合MongoDB

一:新增jar依賴

                <!--MongoDB依賴-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-mongodb</artifactId>
		</dependency>

二;配置

Spring: 
    data:
        mongodb:
          uri: mongodb://localhost:27017/test

三:Controller

@RestController
@RequestMapping(value = "/mongodb")
public class mongoController {
	@Autowired
	private MongoTemplate mt;

	// 修改
	@PostMapping(value="/update")
	public Object update() {
		//查詢的標準,準則
		Criteria ct = new Criteria();
		Query query = new Query(Criteria.where("name").is("翠花"));
		Update update = new Update();
		update.set("name", "茉莉");
		mt.updateFirst(query, update, girl.class);
		return "修改成功";
	}

	// 根據情況查詢
	@GetMapping(value="/find")
	public Object findByCondition() {
		Query query = new Query(Criteria.where("name").is("翠花"));
		List<girl> find = mt.find(query, girl.class);
		return find;
	}

	// 刪除
	@GetMapping(value = "/del")
	public Object del() {
		Criteria Criteria = new Criteria();
		Criteria.where("name").is("玫瑰");
		Query query = new Query(Criteria.where("name").is("玫瑰"));
		mt.remove(query, girl.class);
		return "刪除成功";
	}

	// 儲存
	@GetMapping("/save")
	public String test() {
		girl g1 = new girl("玫瑰", 12);
		girl g2 = new girl("茉莉", 12);
		girl g3 = new girl("鬱金香", 12);
		girl g4 = new girl("菊花", 12);
		girl g5 = new girl("百合", 12);
		mt.save(g1);
		mt.save(g2);
		mt.save(g3);
		mt.save(g4);
		mt.save(g5);
		return "儲存成功";
	}

	// 查詢全部
	@GetMapping(value = "/getAll")
	public List get() {
		List<girl> list = mt.findAll(girl.class);
		return list;
	}
}

!!!!!!!!!!!!!!!!!!