0

I am new to MongoDB and have trouble. I would be very grateful if someone could help me with it.

I have the entity like:

class FileRecord {

private ObjectId id;
private String fileId;
private EnumStatus status;
private Long userId;
private Integer year;
etc.

> }

A file can have many records but only one in the year. I need to get all the last documents by criteria.

I don't understand how to make it right in Spring, but in the mongo query too if to be honest)

I understand how to make criteria for it:

var match = match(Criteria.where("userId").in(userIds).andOperator(Criteria.where("status").in(EnumStatus.availableStatues())));

And group by max:

var group = group("fileId", "year").max("year").as("max_year");

But how to make it to query in one that will return for me Colletion<FileRecord> after aggregation?

If I try it make it this way:

var aggregation = newAggregation(filter, group);

AggregationResults<FileRecord> aggregateResult = 
mongoOperations.aggregate(aggregation, FileRecord.class, FileRecord.class);
Collection<FileRecord> records = aggregateResult.getMappedResults()

I get an exception:

readObjectId can only be called when CurrentBSONType is OBJECT_ID, not when CurrentBSONType is DOCUMENT.;

If someone has an idea I'm interested

Thank you in advance

Takis
  • 8,314
  • 2
  • 14
  • 25

1 Answers1

0

I found the answer)

var group = group("fileId", "year").max("year").as("max_year").first("_id").as("enityId");

I needed to create the projection and after again make request to the DB and get the data that I needed by id. I don't have many of them, so the solution worked for me. But, as I understand, you can add a lot "first", and add the fields you need. And get all by one request