'Spring boot MongoTemplate group without _id
I want a single object from the collection that counts and calculates average.
The collection looks like this:
[{
"_id" : ObjectId("617822b1d128026ff4c76a76"),
"title" : "some title",
"rating" : 4,
...
}
...
]
In mongodb, this is working for me:
db.getCollection('articles').aggregate([
{
$group: {
_id: null,
average: {$avg: "$rating"},
count: {$sum: "$rating"}
}
},
{
$project: {
"average": 1, "count": 1
}
}
])
and returns
{
"_id" : null,
"average" : 3.60419139638543,
"count" : 86.5005935132504
}
But when I try to do this in Spring Boot like this:
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(
Criteria.where("rating").exists(true)
),
Aggregation.group(null)
.avg("rating").as("value")
.count().as("count"),
Aggregation.project("count", "value").andExclude("_id"),
Aggregation.sort(Sort.Direction.DESC, "value")
);
It says:
"java.lang.IllegalArgumentException: AggregationField name must not be null or empty!
What should I do?
Solution 1:[1]
I fixed this without passing anything to group
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(
Criteria.where("rating").exists(true)
),
Aggregation.group()
.avg("rating").as("value")
.count().as("count"),
Aggregation.project("count", "value").andExclude("_id"),
Aggregation.sort(Sort.Direction.DESC, "value")
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ashutosh |
