Tonny Tc
Tonny Tc

Reputation: 930

$or operator with multiple expressions and multiple fields in an expression using Spring Data Reactive MonogoDB

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:

  1. There seems no proper keywords to create a query method (findAllBy(field1AndField2)In???)
  2. If using JSON-based Query Methods, I really do know how to complete the Cloze test...
    @Query("{$or:[(:fields)]}
    Flux<MyDocument> findAllBy????(Flux<???> fields)
    
    

Upvotes: 0

Views: 1071

Answers (1)

Yadhukrishna
Yadhukrishna

Reputation: 842

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

Upvotes: 1

Related Questions