I am new to mongodb. I have a document structure like this in mongo collection
{
orgId: "",
location: "",
companyId: "",
employees: [
{
employeeId: "",
status: "",
startDate: ""
},
{
employeeId: "",
status: "",
promotionDate: ""
}
]
}
And wanted to write a query to find all the documents having location="US", statuses="{L1, L2}" who all promoted before today and remove all the subdocuments matching criteria.
since I don't have IDs here to pull out employees I thought of using aggregation but it's not working.
Date currentTime = Date.from(Instant.now());
MatchOperation locationMatch = Aggregation.match(Criteria.where("location").in(locations));
UnwindOperation unwindOperation = Aggregation.unwind("employees");
MatchOperation logMatch = Aggregation.match(Criteria.where("employees.statuses").in(statuses));
MatchOperation expiryMatch = Aggregation.match(Criteria.where("employees. promotionDate").lt(currentTime));
Aggregation aggregationPipeline = Aggregation.newAggregation(
locationMatch,
unwindOperation,
logMatch,
expiryMatch);
List<Employees> employees =
mongoTemplate.aggregate(aggregationPipeline, Company.class, employees.class)
.getMappedResults();
List<String> employeeList = employees.stream()
.map(emp -> emp.employeeId())
.collect(Collectors.toList());
Update update = new Update().pull("list", Query.query(Criteria.where("value").in(employeeList)));
return mongoTemplate.findAndModify(new Query(), update,
new FindAndModifyOptions().returnNew(true), Company.class);
Is there anyway I can achieve this result in a single mongo operation? or perhaps how would I delete all the subdocuments matching criteria?