Salman Kazmi Salman Kazmi - 1 year ago 157
Java Question

How to store mongodb aggregate query result in spring mongotemplate?

I am using an aggregate query in mongodb to find the sum of an attribute in all the documents present in a collection.


db.conversation.aggregate( [
_id: {"mailBoxId":"$mailBoxId","isHidden":"$isHidden"} ,
messageCount: { $sum:"$messageCount" }

The result returned by Mongodb is fine and is in this format.

"result" : [
"_id" : {
"mailBoxId" : "2",
"isHidden" : false
"messageCount" : 2
"ok" : 1

I just want the messageCount field. I am using MongoTemplate(Spring) class to query the database.

Query retrievalQuery = new Query();
return mongoTemplate.find(retrievalQuery, );

I am confused how to store the resultant object returned by Mongodb and extract a specific field from it.

Pls help.

Answer Source

The way you are trying to use aggregate in mongoTemplate is wrong . Try this i am sure it will help.

Aggregation agg = Aggregation.newAggregation(

System.out.println("Query  ==>>["+agg.toString()+"]");
AggregationResults<AggResultObj> data = mongoTemplate.aggregate(agg, "collectionName", AggResultObj.class);

System.out.println("UnReadMesasgeCode :"+data.getUniqueMappedResult().getUnReadMessagesCount());

The AggResultObj will be looks like

public class AggResultObj{
    String _id;
    int unReadMessagesCount;

    public String get_id() {
        return _id;
    public void set_id(String _id) {
        this._id = _id;
    public int getUnReadMessagesCount() {
        return unReadMessagesCount;
    public void setUnReadMessagesCount(int unReadMessagesCount) {
        this.unReadMessagesCount = unReadMessagesCount;

For more information you can see my blog where i have created a example for the same for your scenario. please click

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download