我有以下MongoDB文档:
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
@AllArgsConstructor
@accessors(chain = true)
@SuperBuilder
@Document(collection = ReasonDocument.COLLECTION)
public class ReasonDocument extends BaseDocument<ObjectId> {
public static final String COLLECTION = "reasons";
@Id
private ObjectId id;
@Indexed
private ObjectId ownerId;
@Indexed
private LocalDate date;
private Type type;
private String reason;
}
我想获取ownerId
中所有带有最新date
的行,并另外过滤掉其中一些。我为此编写了自定义存储库,在其中将聚合与组语句一起使用:
public class ReasonsRepositoryImpl implements ReasonsRepository {
private final MongoTemplate mongoTemplate;
@Autowired
public ReasonsRepositoryImpl(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
public List<ReasonDocument> findReasons(LocalDate date) {
final Aggregation aggregation = Aggregation.newAggregation(
sort(Direction.DESC,"date"),group("ownerId")
.first("id").as("id")
.first("reason").as("reason")
.first("type").as("type")
.first("date").as("date")
.first("ownerId").as("ownerId"),match(Criteria.where("date").lte(date).and("type").is(Type.TYPE_A))
);
return mongoTemplate.aggregate(aggregation,"reasons",ReasonDocument.class).getMappedResults();
}
}
这是一个聪明的查询,但不幸的是,它在测试时返回了损坏的行:
java.lang.AssertionError:
Expecting:
<[ReasonDocument(id=5dd5500960483c1b2d974eed,ownerId=5dd5500960483c1b2d974eed,date=2019-05-14,type=TYPA_A,reason=14),ReasonDocument(id=5dd5500960483c1b2d974ee8,ownerId=5dd5500960483c1b2d974ee8,date=2019-05-15,reason=1)]>
to contain exactly in any order:
<[ReasonDocument(id=5dd5500960483c1b2d974eef,reason=1),ReasonDocument(id=5dd5500960483c1b2d974efc,reason=14)]>
elements not found:
<[ReasonDocument(id=5dd5500960483c1b2d974eef,reason=14)]>
and elements not expected:
<[ReasonDocument(id=5dd5500960483c1b2d974eed,reason=1)]>
返回的id
与ownerId
相同。
谁能说出查询出了什么问题?