2
votes

In feed collection "likeCount" and "commentCount" are two column. I want to get all document where "likeCount" + "commentCount" greater than 100. How can I write the search filter query in Spring Mongo DB?

Below is my sample feed collection data.

{
"_id" : ObjectId("55deb33dcb9be727e8356289"),
"channelName" : "Facebook",
"likeCount" : 2,
"commentCount" : 10,
}

For compare single field we can write search query like :

BasicDBObject searchFilter = new BasicDBObject();
searchFilter.append("likeCount", new BasicDBObject("$gte",100));

DBCursor feedCursor = mongoTemplate.getCollection("feed").find(searchFilter);
2

2 Answers

2
votes

Try this

db.collection.aggregate([{$project:{total:{'$add':["$likeCount","$commentCount"]}}},{$match:{total:{$gt:100}}}])

1
votes

You would need to use the MongoDB Aggregation Framework with Spring Data MongoDB. In Spring Data the following returns all feeds with a combined likes and comments counts greater than 100, using the aggregation framework. :

Entities

class FeedsCount {

    @Id String id;

    String channelName;

    long likeCount;

    long commentCount;

    long totalLikesComments;

    //...
}

Aggregation

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();
  • In the code above, first create a new aggregation via the newAggregation static factory method to which you pass a list of aggregation operations. These aggregate operations define the aggregation pipeline of your Aggregation.
  • As a first step, select the "id", "channelName", "likeCount", "commentCount" fields from the input collection with the project operation and add a new field "totalLikesComments" which is a computed property that stores the sum of the "likeCount" and "commentCount" fields.
  • Finally in the second step, filter the intermediate result by using a match operation which accepts a Criteria query as an argument.
  • Note that you derive the name of the input-collection from the Feed-class passed as first parameter to the newAggregation-Method.