在Spring Mongo DB中过滤搜索查询

时间:2015-09-25 05:52:23

标签: spring mongodb

在Feed集合中,“likeCount”和“commentCount”是两列。我想获取所有文档,其中“likeCount”+“commentCount”大于100.如何在Spring Mongo DB中编写搜索过滤器查询?

以下是我的样本Feed集合数据。

{
"_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);

2 个答案:

答案 0 :(得分:1)

试试这个

db.collection.aggregate([{$项目:{总:{ '$添加':[ “$ likeCount”, “$ commentCount”]}}},{$匹配:{总:{$ GT:100 }}}])

答案 1 :(得分:1)

您需要在Spring Data MongoDB中使用 MongoDB Aggregation Framework 。在Spring Data中,以下内容使用聚合框架返回所有使用组合的赞和评论计数大于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();
  • 在上面的代码中,首先通过 newAggregation 静态工厂方法创建一个新的聚合,并将聚合操作列表传递给该方法。这些聚合操作定义聚合的聚合管道。
  • 首先,使用项目操作从输入集合中选择"id""channelName""likeCount""commentCount"字段,然后添加新字段{{1这是一个存储"totalLikesComments""likeCount"字段之和的计算属性。
  • 最后在第二步中,使用匹配操作过滤中间结果,该操作接受Criteria查询作为参数。
  • 请注意,您将作为第一个参数传递的Feed类的输入集合的名称派生到newAggregation-Method。
相关问题