Below is the code I've been using to project the data I need.
I'm using Spring Data API 4.2.2.
But I'm stuck in projecting a list of projected data.
I'm unable to project the data in the fromCollection into the data in the Document Object.
public List<Document> getOrders(List<String> idList, ZonedDateTime fromDate,ZonedDateTime toDate) {
List<Criteria> criteria = new ArrayList<>();
Query query = new Query();
if (fromDate != null && toDate != null)
criteria.add(Criteria.where("l_appointments.start_datetime").gte(fromDate).lte(toDate));
if (idList != null && !idList.isEmpty())
criteria.add(Criteria.where("account_id").in(idList));
query.addCriteria(new Criteria().andOperator(criteria.toArray(new Criteria[0])));
MatchOperation matchOperation = Aggregation.match(new Criteria().andOperator(criteria.toArray(new Criteria[0])));
AddFieldsOperation addFieldsOperation = Aggregation.addFields().addFieldWithValue("order_id",
ConvertOperators.ToString.toString("$_id")).build();
SortOperation sortOperation = Aggregation.sort(Sort.Direction.valueOf(sortDirection), sortBy);
LookupOperation lookupOperation = Aggregation.lookup()
.from("appointments")
.localField("$order_id")
.foreignField("customer_order_id")
.as("appointments");
ProjectionOperation projectionOperation = Aggregation.project().andInclude("ROOT.customer_order_number",
"first_name", "last_name", "phone_one", "phone_two",
"email", "appointments");
Aggregation aggregation = newAggregation(matchOperation, addFieldsOperation, sortOperation,
lookupOperation, projectionOperation);
return mongoTemplate.aggregate(aggregation, "orders",
Document.class).getMappedResults();
}
Below is the sample output I'm getting:
[
{
"_id": "1",
"first_name": "AMERICA",
"last_name": "",
"phone_one": "5555555555",
"phone_two": "",
"order": "D",
"email": "",
"appointments": [
{
"a": false,
"b": "MANUAL",
"c": "abcd",
"d": "2023-10-19T15:00:00.000+00:00",
"e": "2023-10-20T03:00:00.000+00:00"
},
{
"a": true,
"b": "ORDER",
"c": "abcd",
"d": "2023-12-11T19:00:00.000+00:00",
"e": "2023-12-12T03:00:00.000+00:00"
}
]
},
{
"_id": "2",
"first_name": "ELECTRIC",
"phone_one": "+987654323456",
"order": "D",
"appointments": [
{
"a": true,
"b": "ORDER",
"c": "fettty",
"d": "2023-12-11T15:00:00.000+00:00",
"e": "2023-12-12T03:00:00.000+00:00"
}
]
}
]
Below is the sample response I need:
[
{
"_id": "1",
"first_name": "AMERICA",
"phone_one": "5555555555",
"appointments": [
{
"a": false,
"b": "MANUAL",
"e": "2023-10-20T03:00:00.000+00:00"
},
{
"a": true,
"b": "ORDER",
"e": "2023-12-12T03:00:00.000+00:00"
}
]
},
{
"_id": "2",
"first_name": "ELECTRIC",
"phone_one": "+987654323456",
"appointments": [
{
"a": true,
"b": "ORDER",
"e": "2023-12-12T03:00:00.000+00:00"
}
]
}
]
Thanks in advance!!