美文网首页
spring mongo实现对子文档增删改和统计的实践记录

spring mongo实现对子文档增删改和统计的实践记录

作者: 焦文强 | 来源:发表于2017-06-22 11:39 被阅读467次

1. 用到的文档数据结构

TradeRate文档里面内嵌Label文档


1.Label(标签文档)

/* 1 */

{

"_id" : ObjectId("593e3f0bf8d9771d344547e6"),

"_class" : "com.shuyun.customer.center.domain.Label",

"labelName" : "spring",

"titleId" : NumberLong(71677914),             //标题id

}

/* 2 */

{

"_id" : ObjectId("5940a18436ebf318d4333a61"),

"_class" : "com.shuyun.customer.center.domain.Label",

"labelName" : "mongo",

"titleId" : NumberLong(71677914)

}

2.TradeRate(评价文档)

/* 1*/

{

"_id" : ObjectId("000000010131788772406286"),

"_class" : "com.shuyun.customer.center.domain.TradeRate",

"titleId" : NumberLong(71677914),                                //标题id

"numIid":NumberLong(41808091712)                        //子标题id

"created" : ISODate("2017-06-03T14:48:23.000Z") ,     // 创建时间

"labels" : [                                                      //子文档

{

"_id" : ObjectId("5940a17e36ebf318d4333a5e"),

"labelName" : "spring",                                 //标签名

"titileId" : NumberLong(71677914)             //标题id

},

{

"_id" : ObjectId("5940a18436ebf318d4333a61"),

"labelName" : "mongo",

"titleId" : NumberLong(71677914)

}

]

}

/* 2 */

{

"_id" : ObjectId("000000003370954519376596"),

"_class" : "com.shuyun.customer.center.domain.TradeRate",

"titleId" : NumberLong(71677914),

"numIid":NumberLong(41808091712) ,                       //子标题id

"created" : ISODate("2017-06-08T14:48:23.000Z")

}

```

2. 实现增删改

(1)实现 Label文档的数据保存

```

Label label=new Label();

label.setLabelName("spring");

label.setTitleId(71677914);

mongoTemplate.save(label)

```

(2)实现 Label文档的删除同时删除TradeRate文档里面用到的label数据

这里涉及到了对子文档的删除操作


```

mongoTemplate.remove(Query.query(Criteria.where("_id").is(id)),Label.class);

Query query =newQuery(Criteria.where("titleId").is(titleId));

Update update =newUpdate();

update.pull("labels",Query.query(Criteria.where("id").is(id)));

mongoTemplate.updateMulti(query,update,TradeRate.class);

```

(3)实现 修改Label文档的labelName字段,同时修改TradeRate文档里用到的相应名字

这里涉及到了对子文档的修改操作


mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(label.getId())),Update.update("labelName",label.getLabelName()),Label.class);

Query query = Query.query(Criteria.where("shopId").is(label.getShopId()).and("labels._id").is(newObjectId(label.getId())));Update update = Update.update("labels.$.labelName",label.getLabelName());

mongoTemplate.updateMulti(query,update,TradeRate.class);

(4)实现批量保存或者修改TradeRate的子文档Label

Query query = Query.query(Criteria.where("_id").in(labelSign.getOidList()));

Update update =newUpdate();

Update.AddToSetBuilder builder = update.addToSet("labels");

builder.each(labelSign.getLabels().toArray());

mongoTemplate.updateMulti(query,update,TradeRate.class);

(5)根据相应的条件删除子文档数组中的某个元素

Query query =newQuery(Criteria.where("_id").is(oid));

Update update =newUpdate();

update.pull("labels",Query.query(Criteria.where("id").is(labelId)));

mongoTemplate.updateMulti(query,update,TradeRate.class);

3. 实现根据时间做统计分析

需求:根据相应条件按天统计出TradeRate文档的子文档不同标签的数目(一个月内)

条件:

created: 评价时间        说明:时间范围

titleId: 标题id                 说明:例子:8907067067

numIid:子标题id          说明:子标题list集合

publicListstatisticsLabel(StatisticQueryVO param) {

Date endDate = DateUtils.dayStart(newDate());

Calendar calendar = Calendar.getInstance();

calendar.setTime(endDate);

calendar.add(Calendar.DATE,-30);

Date startDate = calendar.getTime();

/**查询条件*/

DBObject dateObject = BasicDBObjectBuilder.start("$gte",startDate).add("$lt",endDate).get();

BasicDBObject dbObject =newBasicDBObject("titleId",param.getTitleId())

.append("created",dateObject)

.append("labels", newBasicDBObject("$exists", true));

if(param.getGoodIds() !=null&& param.getGoodIds().size() >0) {

dbObject.append("numIid", newBasicDBObject("$in",param.getGoodIds()));

}

DBObject match =newBasicDBObject("$match",dbObject);

/**创建$unwind操作,用于切分数组*/

DBObject unwind =newBasicDBObject("$unwind","$labels");

/** Group操作*/

DBObject groupFields =newBasicDBObject("_id", newBasicDBObject("labelName","$labels.labelName")

.append("date", newBasicDBObject("year", newBasicDBObject("$year","$created"))

.append("month", newBasicDBObject("$month","$created"))

.append("day", newBasicDBObject("$dayOfMonth","$created"))));

groupFields.put("counts", newBasicDBObject("$sum",1));

DBObject group =newBasicDBObject("$group",groupFields);

/**定义显示的结果名称*/

DBObject projectFields =newBasicDBObject();

projectFields.put("date","$_id.date");

projectFields.put("labels", newBasicDBObject("labelName","$_id.labelName").append("countNum","$counts"));

DBObject project =newBasicDBObject("$project",projectFields);

/**对结果再次分组*/

DBObject groupAgainFields =newBasicDBObject("_id","$date");

groupAgainFields.put("labelSum", newBasicDBObject("$push","$labels"));

DBObject reshapeGroup =newBasicDBObject("$group",groupAgainFields);

DBObject sortField =newBasicDBObject("$sort", newBasicDBObject("_id",1));

List dbObjectList = Lists.newArrayList();

dbObjectList.add(match);

dbObjectList.add(unwind);

dbObjectList.add(group);

dbObjectList.add(project);

dbObjectList.add(reshapeGroup);

dbObjectList.add(sortField);

AggregationOutput output =mongoTemplate.getCollection("tradeRate").aggregate(dbObjectList);

List resultList = Lists.newArrayList();

DateModel dateModel;

StatisticResultVO statisticResultVO;

//遍历结果

for(DBObject result : output.results()) {

statisticResultVO =newStatisticResultVO();

dateModel = JsonUtils.parse(result.get("_id").toString(),DateModel.class);

statisticResultVO.setDate(newGregorianCalendar(dateModel.getYear(),dateModel.getMonth()-1,dateModel.getDay()+1).getTime());

statisticResultVO.setLabelSumList(JsonUtils.parse2List(result.get("labelSum").toString(),LabelSum.class));

resultList.add(statisticResultVO);

}

returnresultList;

}

相关文章

网友评论

      本文标题:spring mongo实现对子文档增删改和统计的实践记录

      本文链接:https://www.haomeiwen.com/subject/chnxcxtx.html