Skip field if search input is empty Mongodb

hi! some one have create a dynamic query?

i try to build a query with $or but it seems not work, i have try to build a dynamic quesry via js but i fail. some suggest?

I need to skil "Codice" field if is empty

{
  $or: [
    {
     Codice: {{!search_Cod.value ? 0 : parseInt(search_Cod.value)}},
    },
    {
      Descrizione: { "$regex": {{ !search_description.value ? "" : search_description.value }}, "$options": "i"},
      Cat_merc: {"$regex": {{ !search_cat_merc.value ? "" : search_cat_merc.value }}, "$options": "i"},
    }
  ] 
}

i have try this but return invalid json

{
    Descrizione: { "$regex": {{ search_description.value && !isNaN(search_description.value) ? "" : search_description.value }}, "$options": "i"},
    Cat_merc: {"$regex": {{ !search_cat_merc.value ? "" : search_cat_merc.value }}, "$options": "i"},
    Codice: { {{ search_description.value && isNaN(search_description.value) ? undefined : parseInt(search_description.value) }} }
}

Hey @Mredodos! To summarize, are you looking for the correct Mongo syntax? If so, are any of these posts getting us closer to the type of condition you're looking for? :slight_smile:

https://stackoverflow.com/questions/57034716/querying-to-exclude-empty-values-yet-i-am-getting-those

https://stackoverflow.com/questions/31913868/excluding-from-match-if-data-is-blank-or-null-in-mongodb

https://www.mongodb.com/docs/manual/reference/operator/aggregation/ifNull/

This is what I've done in the past.

[{$match: {
  title: {{ searchTitle.value !== "" ? { $regex: searchTitle.value, $options: 'i' } : {$exists:true} }},
}}]

However, I've found it's much faster to just query for everything from Monogo, and then use filter locally.

i have solved with this

{
    Descrizione: { "$regex": {{ search_description.value && isNaN(search_description.value) ? search_description.value : "" }}, "$options": "i"},
    Cat_merc: {"$regex": {{ !search_cat_merc.value ? "" : search_cat_merc.value }}, "$options": "i"},
    Codice: {{ search_description.value && !isNaN(parseInt(search_description.value)) ?  parseInt(search_description.value) : undefined }},
}
1 Like