We are using MongoDB for a POC and I am stuck with below problem.
We are building a page to show filter options for data. If user selects any filter, then data needs to be filtered as per selection. If there is no filter selected, all the data should be visible on front-end.
One of the filter needs to be implemented on an array in my MongoDB document. I have implemented the filter using $in
operator. If the filter is selected, then correct data is returned, but if no filter is selected, then empty data is returned since $in
has to match at-least one value from specified array and my specified array is empty.
How to resolve this problem?
Sample document in MongoDB
{_id: 1, brands: ["a","b"]}
{_id: 2, brands: ["c","d"]}
{_id: 3, brands: ["a","d"]}
I am using below query on my Spring Boot repository. I am using ReactiveMongoRepository.
@Query("{'brands': { $in: ?1}}")
Flux<LocationDocument> findByQuery(List<String> brands);
Idea is,
if brands
list is empty, all the documents should be returned. If brands
contain something, then it should be filtered.
Please suggest.
2
Answers
You should first check whether the
brands
param is empty, then ignore it, otherwise check for the values in the array. Something like this:You might want o put empty array in single quotes ‘[]’, please try it out. Alsom if the brands is
null
, you might want send an empty array to the query, otherwise add an additional check fornull
, in$or
.