Spring Mongo数据库中的过滤搜索查询
在提要集合中,“likeCount”和“commentCount”是两列。我想获取所有“likeCount”+“commentCount”大于100的文档。如何在Spring Mongo DB中编写搜索过滤器查询 下面是我的示例提要收集数据Spring Mongo数据库中的过滤搜索查询,spring,mongodb,Spring,Mongodb,在提要集合中,“likeCount”和“commentCount”是两列。我想获取所有“likeCount”+“commentCount”大于100的文档。如何在Spring Mongo DB中编写搜索过滤器查询 下面是我的示例提要收集数据 { "_id" : ObjectId("55deb33dcb9be727e8356289"), "channelName" : "Facebook", "likeCount" : 2, "commentCount" : 10, } 对于比较单个字段,我们可
{
"_id" : ObjectId("55deb33dcb9be727e8356289"),
"channelName" : "Facebook",
"likeCount" : 2,
"commentCount" : 10,
}
对于比较单个字段,我们可以编写如下搜索查询:
BasicDBObject searchFilter = new BasicDBObject();
searchFilter.append("likeCount", new BasicDBObject("$gte",100));
DBCursor feedCursor = mongoTemplate.getCollection("feed").find(searchFilter);
试试这个
聚合([{$project:{$total:{'$add':[“$likeCount”,“$commentCount”]}}}},{$match:{$total:{$gt:100}}}}])您需要对Spring数据MongoDB使用。在Spring数据中,下面使用聚合框架返回所有喜欢和评论计数大于100的提要: 实体
class FeedsCount {
@Id String id;
String channelName;
long likeCount;
long commentCount;
long totalLikesComments;
//...
}
聚合
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
Aggregation agg = newAggregation(Feed.class,
project("id", "channelName", "likeCount", "commentCount")
.andExpression("likeCount + commentCount").as("totalLikesComments"),
match(where("totalLikesComments").gt(100))
);
//Convert the aggregation result into a List
AggregationResults<FeedsCount> groupResults
= mongoTemplate.aggregate(agg, FeedsCount.class);
List<FeedsCount> results = groupResults.getMappedResults();
import static org.springframework.data.mongodb.core.aggregation.aggregation.*;
聚合agg=newAggregation(Feed.class,
项目(“id”、“channelName”、“likeCount”、“commentCount”)
.andExpression(“likeCount+commentCount”)。作为(“TotalikeScomments”),
匹配(其中(“Totalikescomments”).gt(100))
);
//将聚合结果转换为列表
聚合结果groupResults
=mongoTemplate.aggregate(聚合,FeedScont.class);
List results=groupResults.getMappedResults();
- 在上面的代码中,首先通过向其传递聚合操作列表的静态工厂方法创建一个新的聚合。这些聚合操作定义了聚合的聚合管道
- 作为第一步,使用项目操作从输入集合中选择
,“id”
,“channelName”
,“likeCount”
字段,并添加一个新字段“commentCount”
,它是一个计算属性,存储“totalikescomments”
和“likeCount”
字段的总和“commentCount”
- 最后,在第二步中,通过使用一个接受条件查询作为参数的匹配操作来过滤中间结果
- 请注意,您从作为第一个参数传递给newAggregation方法的提要类派生输入集合的名称