In MongoDB, I can use $or[{key1:'value11', key2:'value12'}, {key1:'value21', key2:'value22'}, {key1:'value31', key2:'value32'}, ...]
to query several documents which matches at least one of the expressions in the $or
operator. Then how the thing can be done using Spring Data Reactive MonogoDB?
In particular, I define a entity class as:
@Document
public class MyDocument
{
@Id
private String id;
private String field1;
private String field2;
}
And then, the repository interface for the entity:
public interface MyDocumentRepository extends ReactiveMongoRepository<MyDocument, String>
The question now is how to define a method in MyDocumentRepository
to query the documents with field1
and field2
:
findAllBy(field1AndField2)In
???)@Query("{$or:[(:fields)]}
Flux<MyDocument> findAllBy????(Flux<???> fields)
Spring Data MongoDB has support for ReactiveMongoTemplate
. In a repository, you can use this as a connection to MongoDB which can be used with @Autowire
.
In ReactiveMongoTemplate
you can create Criteria
with and
and or
operation like
Query query = new Query();
query.addCriteria(
new Criteria().andOperator(
Criteria.where("field1").exists(true),
Criteria.where("field1").ne(false)
)
);
and this can be passed to MongoDB with the before created instance of ReactiveMongoTemplate
Flux<Foo> result = reactiveMongoTemplate.find(query, Foo.class);
Documentation for use of configuration of ReactiveMongoTemplate
if needed can be found here