skip to Main Content

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


  1. You should first check whether the brands param is empty, then ignore it, otherwise check for the values in the array. Something like this:

    @Query("{ $or : [ { $expr: { $eq: ['?1', []] } } , { brands : { $in: ?1 } } ] }")
    Flux<LocationDocument> findByQuery(List<String> brands);
    

    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 for null, in $or.

    Login or Signup to reply.
  2. Let's say you have a users collection that contains the following documents:
    
    
    
    { "_id": 1, "name": "Alice", "age": 30 }
    { "_id": 2, "name": "Bob", "age": 25 }
    { "_id": 3, "name": "Charlie", "age": 40 }
    If you run the following query with $in and an empty array:
    
    
    db.users.find({ "_id": { $in: [] } })
    You will get an empty result set because there are no values in the empty array to match against the _id values in the collection.
    
    However, if you omit the "_id" field condition, like this:
    
    
    
    db.users.find({})`enter code here`
    You will get all documents in the collection, regardless of the values in any specific field:
    
    { "_id": 1, "name": "Alice", "age": 30 }
    { "_id": 2, "name": "Bob", "age": 25 }
    { "_id": 3, "name": "Charlie", "age": 40 }
    I hope this example helps illustrate the behavior of using $in with an empty array in a MongoDB query.
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search