在SpringBoot项目中使用mongodb
一,配置文件
在application.properties文件中可以使用两种方法
第一,当没有不使用用户名和密码的时候.
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=test
第二,当使用用户名和密码的时候.
spring.data.mongodb.uri=mongodb://user:password@ip:port/database
下面是集群的配置
spring.data.mongodb.uri=mongodb://SGTraker:SG2dTr4ak6erDc@120.26.3.182:27017,120.26.4.12:27017/prodata?replicaSet=sgmongocluster
{
ps:
db.createCollection("log", { capped : true, size : 5242880, max : 5000 } ) //固定大小,环形缓存方式,当空间被占用完了之后会覆盖旧数据
db.createCollection("people", { size: 2147483648 } )
这两个都可以创建表,但是第一个不能删除里面的数据.
}
二,客户端配置.
@Configuration
public class MongoConfiguration {
@Bean
public MongoDatabase mongoDatabase(MongoClient mongoClient, MongoProperties mongoProperties){
return mongoClient.getDatabase(mongoProperties.getDatabase());
}
}
三,业务操作.
@Autowired
private MongoTemplate mongoTemplate;
@Override
public void saveUser(UserEntity userEntity) {
this.mongoTemplate.save(userEntity);
}
@Override
public UserEntity findUserByUserName(String userName) {
Query query=new Query(Criteria.where("userName").is(userName));
UserEntity userEntity=this.mongoTemplate.findOne(query,UserEntity.class);
return userEntity;
}
@Override
public int updateUser(UserEntity userEntity) {
Query query=new Query(Criteria.where("id").is(userEntity.getId()));
Update update=new Update().set("userName",userEntity.getUserName()).set("passWord",userEntity.getPassWord());
WriteResult writeResult=this.mongoTemplate.updateFirst(query,update,UserEntity.class);
if (null!=writeResult){
return writeResult.getN();
}else {
return 0;
}
}
@Override
public void deleteUserById(Long id) {
Query query=new Query(Criteria.where("id").is(id));
this.mongoTemplate.remove(query,UserEntity.class);
}
或者直接这么使用.
@Autowired
private MongoDatabase mongoDatabase;
@GetMapping("actives")
public ResponseEntity getActives(@RequestParam(value = "appIds", required = false) String appIds,
@RequestParam(value = "groupBy", defaultValue = "appid,date") String groupBy,
@RequestParam(value = "startDate") String startDate,
@RequestParam(value = "endDate") String endDate) {
Bson id = extractGroupById(groupBy);
Bson match = extractMatch(startDate, endDate, appIds);
MongoIterable<Document> iterable = mongoDatabase.getCollection("daily_user_actives")
.aggregate(
Arrays.asList(
Aggregates.match(match),
Aggregates.group(
id,
sum("actives", "$actives")
)
)
).map(document -> {
Document newDocument = document.get("_id", Document.class);
newDocument.append("actives", document.getLong("actives"));
return newDocument;
});
List<Document> result = iterable.into(new LinkedList<>());
LOGGER.debug("Results count: {}", result.size());
return ResponseEntity.ok(result);
}