skip to Main Content

I have a query in MongoDB like so

collection.find(
    {$and:[
        {origin:{ $in: countries }}, {brand: {$in: brands}}
    ]}
).toArray();

If both the arrays countries and brands have some values, the query will correctly return documents that have both the specified country and brand. However, if one of these arrays is empty, the query will no longer work. How can I fix this? I want my users to be able to search only by country or only by brand, not always by both. I also have other parameters which should be searchable independently or combined with other parameters. How can I construct a query that will give me the desired output?

3

Answers


  1. Did you try changing to $or?

    collection.find(
        {$or:[
            {origin:{ $in: countries }}, {brand: {$in: brands}}
        ]}
    ).toArray();
    
    Login or Signup to reply.
  2. Try this:

    collection.find(
        {$and:[
          {"origin.0":{$exists:true}},
          {"brand.0":{$exists:true}},
          {origin:{$in:countries}}, 
          {brand:{$in:brands}}
        ]}
    ).toArray();
    

    Simply verification that first element of both array exists.

    Login or Signup to reply.
  3. const query = { $and: [] }; // basic condition (find everything)
    
    if (userRequest.countries?.length > 0) { // if countries is not empty array
      query.$and.push({ origin: { $in: userRequest.countries} })
    }
    
    if (userRequest.brands?.length > 0) {
      query.$and.push({ brand: { $in: userRequest.brands} })
    }
    // other conditions may be added further correspodingly
    
    const result = await collection.find(query);
    

    In the example above I used ephemeral object userRequest to illustrate object with inputs for filtering. The main idea is that you have the general query object with $and array for all the conditions inside (but you may modify the query object as well). Then if user specified some filters – you just need to add corresponding condition to the conditions array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search