由於剛剛接觸mongodb,很多語法還不是很了解,寫的不好的地方請大佬指出
查詢的demo數據
{ "_id":Object("xxxxxxxx"), "contentList":[ "id":"xxxx", "type":2 ], [ "id":"xxxx", "type":2 ] }
查詢方法,使用聚合aggregate查詢
match:將查詢的contentList的size大於2的查出來
unwind:將集合根據contentList分組
match:再查出所有contentList的type為2的結果
group:再根據_id和total分組,total根據_id計算總數
match:過濾掉contentList的type小於3條的數據
project:結果集過濾,我只要id字段
db.getCollection('momPublishRecently').aggregate([ {"$match": {"contentList.2": {"$exists": 1}}}, {"$unwind": "$contentList"}, {"$match": {"contentList.type": 2}}, {"$group": {"_id":"$_id", "total": {"$sum":1}}}, {"$match": {"total": {"$gte": 3}}}, {"$project": {"total":0}} ]);
下面是springboot中的寫法
Aggregation agg = Aggregation.newAggregation( Aggregation.match(Criteria.where("contentList.2").exists(true)), Aggregation.unwind("contentList"), Aggregation.match(Criteria.where("contentList.type").is(2)), Aggregation.group("_id").count().as("total"), Aggregation.match(Criteria.where("total").gte(3)), Aggregation.project("_id") ); AggregationResults<IdDTO> results = getMongoTemplate().aggregate(agg, "表名", IdDTO.class); List<IdDTO> list = results.getMappedResults(); List<ObjectId> idList = new ArrayList<>();
//這里轉成object類型 if (!list.isEmpty()) { list.stream().forEach(idDTO -> { idList.add(new ObjectId(idDTO.getId())); }); }
剛剛接觸就要求寫這樣的,還是有點吃力的,花了不少時間,踩了不少mongo的坑
感謝以下資料:
https://www.cnblogs.com/zhoujie/p/mongo1.html
https://docs.spring.io/spring-data/mongodb/docs/2.0.5.RELEASE/reference/html/#mongo.aggregation