Using
aggregation in spring mongo template is quit easy and interesting
.Before going foreword let's see a example of aggregation in mongo db
console client.
If
have collection "messages" in mongo db where i have fields
like mailboxId and unreadMessageCount and some other fields like
isVisible .
Then
the aggregate query for Monog DB console will be like
Console Query:
db.messages.aggregate( [
{
"$match":{"mailboxId":"1","isVisible":true}
},
{
"$group":
{
"_id": "$mailBoxId",
"unReadMessagesCount": { "$sum":"$unReadMessagesCount" }
}
}
]);
Console Result :
/* 1 */
{
"result" : [
{
"_id" : "1",
"unReadMessagesCount" : 12
}
],
"ok" : 1.0000000000000000
}
Aggrigate query in
mongo db give list of result objects ._id is mendatory in $group
Aggrigate
in Spring Mongo Template
To get the same
result using mongo template we need to create same query object in
our java code and we also need a java class to parsh the result and
to fetch values.
Lets say we have
java class AggResultObj.java
to fetch result object
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;
}
}
Then
use the following code to populate aggrgated result in form of this
object. Use the following code sanippet.
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.data.mongodb.core.MongoTemplate;
import
org.springframework.data.mongodb.core.aggregation.Aggregation;
import
org.springframework.data.mongodb.core.aggregation.AggregationResults;
import
org.springframework.data.mongodb.core.query.Criteria;
public
class
DummyTest {
@Autowired
MongoTemplate
mongoTemplate;
public
void
test() {
Aggregation
agg
= Aggregation.newAggregation(
Aggregation.match( Criteria.where("mailBoxId").is("1").and("isVisible").is(false)), Aggregation.group("$mailBoxId").sum("$unReadMessagesCount").as("unReadMessagesCount")
);
System.out.println("Query
==>>["+agg.toString()+"]");
AggregationResults<AggResultObj>
data
= mongoTemplate.aggregate(agg,
"messages",
AggResultObj.class);
System.out.println("UnReadMesasgeCode
:"+data.getUniqueMappedResult().getUnReadMessagesCount());
}
}
No comments:
Post a Comment