spring mongo實現(xiàn)對子文檔增刪改和統(tǒng)計的實踐記錄

1. 用到的文檔數(shù)據(jù)結(jié)構(gòu)

TradeRate文檔里面內(nèi)嵌Label文檔


1.Label(標(biāo)簽文檔)

/* 1 */

{

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

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

"labelName" : "spring",

"titleId" : NumberLong(71677914), ? ? ? ? ? ? //標(biāo)題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), ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//標(biāo)題id

"numIid":NumberLong(41808091712) ? ? ? ? ? ? ? ? ? ? ? ?//子標(biāo)題id

"created" : ISODate("2017-06-03T14:48:23.000Z") , ? ? // 創(chuàng)建時間

"labels" : [? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //子文檔

{

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

"labelName" : "spring", ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //標(biāo)簽名

"titileId" : NumberLong(71677914) ? ? ? ? ? ? //標(biāo)題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) , ? ? ? ? ? ? ? ? ? ? ? //子標(biāo)題id

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

}

```

2. 實現(xiàn)增刪改

(1)實現(xiàn) Label文檔的數(shù)據(jù)保存

```

Label label=new Label();

label.setLabelName("spring");

label.setTitleId(71677914);

mongoTemplate.save(label)

```

(2)實現(xiàn) Label文檔的刪除同時刪除TradeRate文檔里面用到的label數(shù)據(jù)

這里涉及到了對子文檔的刪除操作


```

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)實現(xiàn) 修改Label文檔的labelName字段,同時修改TradeRate文檔里用到的相應(yīng)名字

這里涉及到了對子文檔的修改操作


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)實現(xiàn)批量保存或者修改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)根據(jù)相應(yīng)的條件刪除子文檔數(shù)組中的某個元素

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. 實現(xiàn)根據(jù)時間做統(tǒng)計分析

需求:根據(jù)相應(yīng)條件按天統(tǒng)計出TradeRate文檔的子文檔不同標(biāo)簽的數(shù)目(一個月內(nèi))

條件:

created: 評價時間 ? ? ? ?說明:時間范圍

titleId: 標(biāo)題id ? ? ? ? ? ? ? ? 說明:例子:8907067067

numIid:子標(biāo)題id ? ? ? ? ?說明:子標(biāo)題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);

/**創(chuàng)建$unwind操作,用于切分?jǐn)?shù)組*/

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);

/**定義顯示的結(jié)果名稱*/

DBObject projectFields =newBasicDBObject();

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

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

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

/**對結(jié)果再次分組*/

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;

//遍歷結(jié)果

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;

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,545評論 19 139
  • MongoDB 一、安裝 Windows下,下載安裝包并安裝 在安裝盤的根目錄下,新建data文件夾,里面新建lo...
    Plissmile閱讀 5,556評論 0 4
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc閱讀 2,991評論 0 0
  • “字句,無論是發(fā)聲說出來的或是沒有說出來的,而只是以思想的形式存在,都會在你身上投下一個幾乎像催眠一樣效果的魔咒。...
    candycoin閱讀 181評論 0 0
  • 最近一起玩了十多年的好友突然失去聯(lián)系了,百感交集,憂心忡忡…… 朋友是一個不善言辭的人,什么事憋在心里,遇到天大的...
    金格格閱讀 216評論 0 0

友情鏈接更多精彩內(nèi)容