I am able to execute mongo query on mongo compass with below aggregation but I am not able to execute and get same result on Spring boot application
[
{
$match: {
$and: [
{
channelId: {
$in: [1001],
},
},
],
},
},
{
$facet: {
operationTypes: [
{
$group: {
_id: "$operationType",
count: { $sum: 1 },
},
},
{
$project: {
_id: 0,
operationType: "$_id",
count: 1,
},
},
],
states: [
{
$group: {
_id: "$state",
count: { $sum: 1 },
},
},
{
$project: {
_id: 0,
state: "$_id",
count: 1,
},
},
],
results: [
{
$group: {
_id: "$result",
count: { $sum: 1 },
},
},
{
$project: {
_id: 0,
result: "$_id",
count: 1,
},
},
],
},
},
]
I have tried to create list of AggregationOperation
and then call as below and it didn’t work
public List<AggregationResultTest> getAggregation(Aggregation aggregation) {
AggregationResults<AggregationResultTest> results = mongoTemplate.aggregate(aggregation,COLLECTION_NAME,
AggregationResultTest.class);
return results.getMappedResults();
}
I have tried to use Mongo Compass EXPORT TO LANGAUGE
but it also didn’t work. Here is what EXPORT TO LANGUAGE
button returns
import java.util.Arrays;
import org.bson.Document;
import java.util.Arrays;
import org.bson.Document;
Arrays.asList(new Document("$match",
new Document("channelId", 1001L)),
new Document("$facet",
new Document("operationTypes", Arrays.asList(new Document("$group",
new Document("_id", "$operationType")
.append("count",
new Document("$sum", 1L))),
new Document("$project",
new Document("_id", 0L)
.append("operationType", "$_id")
.append("count", 1L))))
.append("states", Arrays.asList(new Document("$group",
new Document("_id", "$state")
.append("count",
new Document("$sum", 1L))),
new Document("$project",
new Document("_id", 0L)
.append("state", "$_id")
.append("count", 1L))))
.append("results", Arrays.asList(new Document("$group",
new Document("_id", "$result")
.append("count",
new Document("$sum", 1L))),
new Document("$project",
new Document("_id", 0L)
.append("result", "$_id")
.append("count", 1L))))))
I could find a single example on mongo docs 4.4 but I couldn’t understand very well. Can someone help me how can I implement that aggregation on Spring boot application?
IMPORTANT: Repository must be as below
@Repository
public class OperationHistoryRepository {
private final MongoTemplate mongoTemplate;
// Aggrigation method should be in here
}
The problem still exists
1