1

I have a document like that:

'subject' : {
'name' :"...."
'facebookPosts':[

 {
 date:"14/02/2017 20:20:03" , // it is a string
 text:"facebook post text here",
 other stuff here  

 }

]

}

and I want to count the facebookPosts within a specific objects that their date field contains e.g "23/07/2016".

Now, I do that by extracting all the documents and count in the client side (spring ) , But I think that's not efficient.

1 Answer 1

2

You need to aggregate your results.

final Aggregation aggregation = Aggregation.newAggregation(
                    Aggregation.match(Criteria.where("facebookPosts.date").regex(REGEX)),
                    Aggregation.unwind("facebookPosts"),
                    Aggregation.group().count().as("count"));

Regex might not be the best solution, just an example.

unwind will split array into separate elements you can then count.

Create a class that will hold the count, something like:

public class PostCount {
    private Long count;
    // getters, setters
}

And then execute it like this:

AggregationResults<PostCount> postCount = mongoTemplate.aggregate(aggregation, Subject.class, PostCount.class);
long count = postCount.getMappedResults().get(0).getCount();
Sign up to request clarification or add additional context in comments.

11 Comments

Yes I find this doing the job, but what if I want just to count the facebookPosts that satisfies the condition, I mean i want just to count to count them without getting them and counting them myself.
mongoTemplate.count(query, clazz)
will it count the subjects or the facebookPosts within them ?
Updated the answer, I didn't read your question correctly, sorry
there still a small problem in this line PostCount postCount = mongoTemplate.aggregate(aggregation, Subject.class, PostCount.class); it tell me "cannot convert from AggregationResult<PostCount> to PostCount
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.