标签:pre 使用 地方 release exist mongod criteria 好的 sem
由于刚刚接触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
标签:pre 使用 地方 release exist mongod criteria 好的 sem
原文地址:https://www.cnblogs.com/oldboyooxx/p/12041524.html