I was trying to sort documents by last interaction. meta_data.access_times is an array that update every time when user interacts and new date object append to the last element of the array. Is there any way to sort by array's last element?
Attempt 1 :
private Aggregation makeQuery(String userId) {
return newAggregation(
match(Criteria.where("user_id").is(userId)),
sort(Sort.Direction.DESC, "$meta_data.access_times"),
group(Fields.fields().and("first_name", "$meta_data.user_data.first_name").and("last_name", "$meta_data.user_data.last_name").and("profile_pic", "$meta_data.user_data.profile_pic").and("user_id", "$user_id").and("access_times", "$meta_data.access_times"))
);
}
Attempt 2 :
private Aggregation makeQuery(String userId) {
return newAggregation(
match(Criteria.where("user_id").is(user_id)),
group(Fields.fields().and("first_name", "$meta_data.user_data.first_name").and("last_name", "$meta_data.user_data.last_name").and("profile_pic", "$meta_data.user_data.profile_pic").and("user_id", "$user_id")).max("$meta_data.access_times").as("access_time"),
sort(Sort.Direction.DESC, "access_time")
);
}
sample meta_data array in document
"meta_data" : { "access_times" : [
ISODate("2017-06-20T14:04:14.910Z"),
ISODate("2017-06-22T06:27:32.210Z"),
ISODate("2017-06-22T06:27:35.326Z"),
ISODate("2017-06-22T06:31:28.048Z"),
ISODate("2017-06-22T06:36:19.664Z"),
ISODate("2017-06-22T06:37:00.164Z")
] }
groupis throwing me as it's not clear what to expect. Mostly since it's not valid. How about showing whole documents ( just 2 or 3 ) and what you expect to get as your query result. That would be clearer to interpret than your query attempt. The date part I already understand.