I'd like to use Spring Data MongoDB to execute the following query but I stuck on the project operation and I need some help with it.
Here's a query to translate:
db.getCollection("employee_salaries").aggregate([
{ $match: {
salaries: {
$elemMatch: {
"to_date": { $gte: "1985-01-01" } ,
"to_date": { $lte: "1986-01-01" }
}
}
}},
{ $project: {
salaries: {
$filter: {
input: "$salaries",
as: "salaries",
cond: {$and: [
{ $gte: ["$$salaries.to_date", "1985-01-01"]},
{ $lt: ["$$salaries.to_date", "1986-01-01"]}
]}
}
}
}},
{ $unwind: "$salaries"},
{ $group: {
_id: "$null",
"total_salary": { $sum: "$salaries.salary"}
}}
])
And here's my attempt to do so:
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SimpleService {
private final MongoTemplate mongoTemplate;
public Document aggregation() {
MatchOperation matchOperation = match(Criteria.where("salaries").elemMatch(Criteria.where("to_date").gte("1985-01-01").lte("1986-01-01")));
ProjectionOperation projectionOperation = project("salaries");
// other operations
UnwindOperation unwindOperation = unwind("salaries");
Document rawResults = mongoTemplate.aggregate(newAggregation(
matchOperation,
// other operations...
), Salaries.class, String.class).getRawResults();
return totalSalaryInOneYear;
}
}