Hi
I am totally new to MongoDB. I need help to improve my Java Query. The query is to get all the child array elements to a document with highest time for a distinct region. Since I use Accumulators.first I need to sort first. My question is: is there a way to skip the sorting part but still get the correct child array for a distinct region with the highest time ?
Bson match = Aggregates.match(
Filters.eq("country._id", countryId)
);
Bson sort = Aggregates.sort(
Indexes.descending("time", "region._id")
);
Bson group = Aggregates.group(
"region._id",
Accumulators.max("time", "$time"),
Accumulators.first("contentList", "$contentList")
);
List<Data> dataList = dataMongoCollection.aggregate(
Arrays.asList(
match,
sort,
group
)
).into(new ArrayList<>());
Many thanks in advance
Sample document:
{
"_id":"ObjectId(""60"")",
"contentList":[
{
"colors":[
{
"displayName":"Red",
"reference":"red_0",
"value":"red"
}
],
"country":{
"_id":"countryId",
"name":"Sweden"
},
"region":{
"_id":"regionId",
"name":"Stockholm"
},
"score":20002.4,
"time":NumberLong(16237),
"weights":[
{
"displayName":"Red",
"reference":"weight_0",
"value":0.08
}
]
}
],
"country":{
"_id":"c_0",
"name":"Sweden"
},
"granularity":"PT15M",
"region":{
"_id":"r_0",
"name":"Stockholm"
},
"time":NumberLong(1623751979098)
}