0

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)
    
    
Tonny Tc
  • 852
  • 1
  • 12
  • 37
  • you can use reactive mongo template instead, right? If so then we can write the query with Criteria – Captain Levi Aug 23 '20 at 08:19
  • @CaptainLevi Thanks a lot for your kind information. But I'm not familiar with `ReactiveMongoTemplate` and also how to build a criteria of &or operator. Could you please provide some more detail info. ? – Tonny Tc Aug 24 '20 at 02:13
  • You can configure it with https://www.baeldung.com/spring-data-mongodb-reactive#mongoTemplate and use Criteria with `and` and `or` operation similar to https://stackoverflow.com/a/33546797/6777170 , let me know if this works for you so I could write it as an answer for better visibility for people with similar problem – Captain Levi Aug 24 '20 at 06:02
  • @CaptainLevi Yes, it really works! Furthermore, I found that the `ReactiveMongoTemplate` bean can be automatically wired without defining it in configuration class. Thanks a lot for your help. – Tonny Tc Aug 24 '20 at 07:02

1 Answers1

1

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

Captain Levi
  • 804
  • 7
  • 18