Salman Kazmi Salman Kazmi - 3 months ago 22
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.

Query:

db.conversation.aggregate( [
{
$match:{
$and:[{"mailBoxId":"1","isHidden":false}]
}
},
{
$group:
{
_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();
retrievalQuery.addCriteria(Criteria.where("mailBoxId").is(userId).and("isHidden").is(false));
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

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

Aggregation agg = Aggregation.newAggregation(
        Aggregation.match(
                Criteria.where("mailBoxId").is("1").and("isHidden").is(false)),
        Aggregation.group("$mailBoxId").sum("$unReadMessagesCount").as("unReadMessagesCount")
    );


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 https://satishkumardangi.blogspot.in/2016/09/using-mongo-db-aggregation-with-spring.html