I’m a complete beginner with MongoDB and we use MongoTemplate in our project.
I have a collection with documents in this form:
{
"_id" : ObjectId('...'), // This is generated automatically by MongoTemplate, I suppose
"key" : 0,
"value" : {
(complex object)
}
"timestamp" : 1668584029237
...
}
The tricky part for me is that we can have documents with the same “key” that are outdated (can be judged by the “timestamp”).
I’d like to to query all documents in the database, but in the case of documents with the same “key”, then only the one with the latest timestamp (the greatest number) should be returned.
So far I’ve written this:
List<AggregationOperation> aggregations = new ArrayList<>();
...
aggregations.add(sort(Sort.by(DESC, "timestamp")));
aggregations.add(group("key").first("timestamp").as("timestamp"));
final List<Map> result = mongoTemplate.aggregate(newAggregation(aggregations), tableName, Map.class).getMappedResults();
I know that I’m very close to the solution, but I cannot manage to get what I want by the group method Please help.
Note: I need to return all fields expect “_id”