【发布时间】:2020-11-22 06:05:11
【问题描述】:
我想从带有 mongodb 和 spring boot 的数组中获取一个具有特定字段(版本)的嵌入式文档。 这是数据结构:
{
"_id": 5f25882d28e40663719d0b52,
"versions": [
{
"versionNr": 1
"content": "This is the first Version of some Text"
},
{
"versionNr": 2
"content": "This is the second Version of some Text"
},
...
]
...
}
这是我的实体:
@Data
@Document(collection = "letters")
public class Letter {
@Id
@Field("_id")
private ObjectId _id;
@Field("versions")
private List<Version> versions;
}
//There is no id for embedded documents
@Data
@Document(collection = "Version")
public class Version{
@Field("content")
private String content;
@Field("version")
private Long version;
}
这是不起作用的查询。我认为“加入”是不正确的。但无法找出正确的方法。
public Optional<Version> findByIdAndVersion(ObjectId id, Long version) {
Query query = new Query(Criteria.where("_id").is(id).and("versions.version").is(version));
return Optional.ofNullable(mongoTemplate.findOne(query,Version.class,"letters"));
}
}
编辑:这是一个有效的聚合,我确信它不是一个很好的解决方案,但它有效
@Override
public Optional<Version> findByIdAndVersion(ObjectId id, Long version) {
MatchOperation match = new MatchOperation(Criteria.where("_id").is(id).and("versions.version").is(version));
Aggregation aggregate = Aggregation.newAggregation(
match,
Aggregation.unwind("versions"),
match,
Aggregation.project()
.andInclude("versions.content")
.andInclude("versions.version")
);
AggregationResults<Version> aggregateResult = mongoTemplate.aggregate(aggregate, "letters", Version.class);
Version version = aggregateResult.getUniqueMappedResult();
return Optional.ofNullable(mongoRawPage);
}
【问题讨论】:
标签: spring mongodb spring-boot