1.引入maven 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.在application.yml进行连接信息配置
srpring:
data:
mongodb:
uri: mongodb://yangxiaohui:Yangxiaohui227@106.52.85.248:27017/shopdb?maxPoolSize=256 -- 注释:uri的格式:mongodb://username:password@IP:port/database?maxPoolSize=256
3.mysql中的一张表,在mysql数据库中会有一个实体(entiy/pojo/domain)跟其对应,同理mango中的collection(表) 也会有一个实体跟其对应:
//创建一个order表如下:
@Document(collection = "order") //贴有该注解的字符会被映射为对应的集合名字
public class ShopMongoOrder {
@Id //贴有Id注解,生成mongodb的collection对象后,被贴注解的字段就是唯一主键,不能重复
private String orderId;
private String orderTitle;
private BigDecimal orderTotalAmount;
private BigDecimal orderPayAmount;
private String createTime;
private String finishTime;
private String deliveryTime;
@Indexed(unique = false) //索引的创建
private Integer orderStatus;
@Field(value ="paymentStatus" ) //如果没添加这个注解的话,在mongodb中使用的是payStatus字段名称
private Integer payStatus;
private String customerId;
/**
* 日期格式如果不想用String类型表示,可以用下面的格式化方式
* @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;//最新浏览时间
*
*
*/
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getOrderTitle() {
return orderTitle;
}
public void setOrderTitle(String orderTitle) {
this.orderTitle = orderTitle;
}
public BigDecimal getOrderTotalAmount() {
return orderTotalAmount;
}
public void setOrderTotalAmount(BigDecimal orderTotalAmount) {
this.orderTotalAmount = orderTotalAmount;
}
public BigDecimal getOrderPayAmount() {
return orderPayAmount;
}
public void setOrderPayAmount(BigDecimal orderPayAmount) {
this.orderPayAmount = orderPayAmount;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getFinishTime() {
return finishTime;
}
public void setFinishTime(String finishTime) {
this.finishTime = finishTime;
}
public String getDeliveryTime() {
return deliveryTime;
}
public void setDeliveryTime(String deliveryTime) {
this.deliveryTime = deliveryTime;
}
public Integer getOrderStatus() {
return orderStatus;
}
public void setOrderStatus(Integer orderStatus) {
this.orderStatus = orderStatus;
}
public Integer getPayStatus() {
return payStatus;
}
public void setPayStatus(Integer payStatus) {
this.payStatus = payStatus;
}
}
//单条插入
@Service
public class MangodbService {
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private ShopOrderMastMapper orderMastMapper;
//新增
public void insertOrder(String orderId){
ShopMongoOrder shopMongoOrder = orderMastMapper.selectMongoOrderByOrderId(orderId);
if(null!=shopMongoOrder){
mongoTemplate.insert(shopMongoOrder); //调用的是insert(T objectToSave)该方法,因为T是实体类,通过注解就知道查到哪个collection了,mango不像mysql一样需要先创建表,它不用,第一条插入的数据,发现没有对应的collection就会创建
}
}
}
//插入第一条数据后:
重复插入后会报错:
//批量新增
//批量插入
public void insertAll(){
List<ShopMongoOrder> shopMongoOrders = orderMastMapper.selectOrderList();
Collection<ShopMongoOrder> mongoOrders = mongoTemplate.insertAll(shopMongoOrders);
return ;
}
//删除单条数据
//删除单条
public void deleteByOrderId(String orderId){
ShopMongoOrder shopMongoOrder = orderMastMapper.selectMongoOrderByOrderId(orderId);
mongoTemplate.remove(shopMongoOrder);
}
//根据条件删除数据
public void deleteByOrderId(String orderId){
Criteria c = Criteria.where("orderId").is(orderId); //相当于mysql的where orderId="ddd"
Query query = new Query(c);
DeleteResult ret = mongoTemplate.remove(query,ShopMongoOrder.class);
}
//单条修改
//更新订单
public void updateByOrderId(String orderId){
//使用updateFirst(Query query, Update update, Class<?> entityClass)该方法,updateFirst和update方法的区别是:updateFirst只更改查询到的第一条,update是更改所有满足条件的
//new Update().set("orderTitle", "iphone").set("a","b") 可以使用链式表达式
UpdateResult updateResult = mongoTemplate.updateFirst(new Query(Criteria.where("orderId").is(orderId)), new Update().set("orderTitle", "iphone"), ShopMongoOrder.class);
}
//查找单条数据
//查找
public ShopMongoOrder selectOrderId(String orderId){
//findOne(Query query, Class<T> entityClass)
ShopMongoOrder mongoOrder = mongoTemplate.findOne(new Query(Criteria.where("orderId").is(orderId)), ShopMongoOrder.class);
return mongoOrder;
}
//高级查询: 排序 分页
public List<ShopMongoOrder> getList(){
Query query = new Query();
Criteria criteria =new Criteria();
//下面条件相当于select * from order where orderStatus in(16,32) and payStatus=4 and finishTime<=2019-07-05 00:00:00 and (customerId=139 or customerId=1360)
criteria.and("orderStatus").in(16, 32).andOperator(Criteria.where("payStatus").is(4)).and("finishTime").lte("2019-07-05 00:00:00")
.orOperator(Criteria.where("customerId").is("139"),Criteria.where("customerId").is("1360"));
//1360
query.addCriteria(criteria);
System.out.println(JSON.toJSONString(criteria));
long count = mongoTemplate.count(query, ShopMongoOrder.class); //计算总数,用于算法分页数
System.out.println(count);
int pageNum=1;
int pageSize=20;
int pageTotal=(int) (count%pageSize==0?count/pageSize:count/pageSize+1); //总页数
System.out.println(pageTotal);
int offset=(pageNum-1)*pageSize;
query.with(Sort.by(Sort.Order.desc("deliveryTime"))); //排序逻辑
query.skip(offset).limit(pageSize); // 分页逻辑
List<ShopMongoOrder> shopMongoOrders = mongoTemplate.find(query, ShopMongoOrder.class);
//List<String> customerId = mongoTemplate.findDistinct(query, "customerId", ShopMongoOrder.class, String.class); //查询用户编号,去重
return shopMongoOrders;
}
//聚合操作
public void aggress(){
//java的bigDeciaml类型在mongodb中会变成字符串,所以对bigDeciaml进行sum操作,永远都是返回0
//match是条件:match在group后面就相当于where 语句,在后面相当于having语句,sort要在group后面才有意义
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.group("orderStatus").count().as("total")
.sum("orderPayAmount").as("payAmount")
.first("orderStatus").as("orderStatus")
).withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());
//如果不加first的时候,取不到orderStatus的值,所以加了后,分组的值才会有数据
//Aggregation.newAggregationOptions().allowDiskUse(true)是用来解除mongodb 查询数据默认占用最大内存的(默认100M).不然会抛出异常:
AggregationResults<OrderComputeInfo> order = mongoTemplate.aggregate(aggregation, "order", OrderComputeInfo.class);
List<OrderComputeInfo> mappedResults = order.getMappedResults();
System.out.println(mappedResults);
System.out.println(order);
}