Reputation: 31
I wrote mongodb query. And am facing some issue while converting it in spring boot using aggregation class.So, please help me, i want it to convert it in spring boot using aggregation class.
db.api_audit.aggregate([{
$match: {
merchant_id: '015994832961',
request_time: {$gte: ISODate("2017-05-11T00:00:00.0Z"),
$lt: ISODate("2017-05-12T00:00:00.0Z")}}},
{
$group:
{
_id: {
SERVICE_NAME: "$service_name",
STATUS: "$status"
},
count: {
"$sum": 1
}
}
}, {
$group: {
_id: "$_id.SERVICE_NAME",
STATUSCOUNT: {
$push: {
Service_name: "$_id.STATUS",
count: "$count"
}
}
}
},
{ $sort : { "STATUSCOUNT.count" : -1} }
])
Below is the db query response
{
"_id" : "sendOTP",
"STATUSCOUNT" : [
{
"status" : "SUCCESS",
"count" : 2.0
}
]
}
Thanks in advance.
Upvotes: 0
Views: 784
Reputation: 3815
First you create all the required operations and then you add them to an aggregation pipeline. Then you feed it to an autowired mongotemplate.
Something like this:
@Autowired
private final MongoTemplate mongoTemplate;
void aggregate()
{
Criteria match = where("merchant_id").is("015994832961").andOperator(where("request_time").gte(Date.parse("2017-05-11T00:00:00.0Z")).lt(Date.parse("2017-05-11T00:00:00.0Z")));
GroupOperation groupOperation1 = group(fields().and("SERVICE_NAME").and("STATUS")).count().as("count");
GroupOperation groupOperation2 = ...//(not sure how push works here, but it should not be hard to figure out)
SortOperation sortOperation = sort(DESC, "STATUSCOUNT.count");
Aggregation aggegation = Aggregation.newAggregation(match, groupOperation1, groupOperation2, sortOperation);
List<Result> results = mongoTemplate.aggegate(aggregation, ObjectOfCollectionToRunOn.class, Result.class).getMappedResults();
}
Upvotes: 2