英文:
Spring ReactiveMongoTemplate querying objects with embedded objects
问题
我的模型是一个包含不同类型对象集合的对象,
class A {
String id;
String field1;
Set<B> beesInA;
}
class B {
String id;
String name;
}
我想要找到一个 B 类的实例,其 id 为 idB,属于一个 A 类的实例,其 id 为 idA,即
SELECT B WHERE A.id = idA and A.beesInA.id = idB
只有 A 类是一个带有相应的仓库 RepoA
的 document
,该仓库 extends ReactiveMongoRepository<A, String>
我应该如何使用 ReactiveMongoTemplate
为 RepoA
编写查询,以根据上述条件返回 Mono<B>
?
同样地,如果使用上述条件找到一个 B 的实例,我应该如何更新它?
英文:
My model is an object with a collection of objects of a different type,
class A {
String id;
String field1;
Set<B> beesInA;
}
class B {
String id;
String name;
}
I want to find an instance of B whose id is idB which belongs to an instance of A whose id is idA i.e.
SELECT B WHERE A.id = idA and A.beesInA.id = idB
Only class A is a document
with a corresponding repository RepoA
that extends ReactiveMongoRepository<A, String>
How do I write a query using ReactiveMongoTemplate
for RepoA
that will return Mono<B>
according to the aforementioned criteria?
Similarly how do I update an instance of B that is found using the above criteria?
答案1
得分: 2
感谢 Oliver Drotbohm 的 答案,我成功获得了所需的结果。
Query query = Query.query(Criteria.where("id").is("idA").and("beesInA.id").is("idB"));
query.fields().include("beesInA.$");
template.findOne(query, A.class)
.flatMapIterable(A::getBeesInA)
.single();
更新特定 B 实例的方法非常类似。
Query query = Query.query(Criteria.where("id").is("idA").and("beesInA.id").is("idB"));
Update update = new Update().set("beesInA.$", updatedBObject);
template.findAndModify(query,
update,
new FindAndModifyOptions().returnNew(true),
A.class)
.flatMapIterable(A::getBeesInA)
.filter(b -> b.getId().equalsIgnoreCase("idB"))
.single();
这个 帖子 包含了使用 ReactiveMongoTemplate
与 ReactiveMongoRepository
的完整信息。
英文:
Thanks to an answer from Oliver Drotbohm I was able to get the result I needed
Query query = Query.query(Criteria.where("id").is("idA").and("beesInA.id").is("idB"));
query.fields().include("beesInA.$");
template.findOne(query, A.class).flatMapIterable(A::getBeesInA).single();
The update of a particular instance of B is very similar
Query query = Query.query(Criteria.where("id").is("idA").and("beesInA.id").is("idB"));
Update update = new Update().set("beesInA.$", updatedBObject);
template.findAndModify(query,
update,
new FindAndModifyOptions().returnNew(true),
A.class)
.flatMapIterable(A::getBeesInA)
.filter(b -> b.getId().equalsIgnoreCase("idB")
.single();
This post has complete info on using ReactiveMongoTemplate
with ReactiveMongoRepository
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论