vendredi 6 mars 2020

Exclude field dynamically from $match, $and in MongoDB

I'm trying to implement Search with filters. Search includes 'is_published' & 'title'. For this search result I want to apply filters like 'size', 'height', 'format' using $match & $and. I may include either of these filters or none.

{"$match": {"is_published": {"$ne": 2}}},
{"$match": {"$or": [
                    {"title": "Flower"},
                ]}},
{"$match": {"$and": [
                    {"size": <dynamic_value_from_front_end>},
                    {"height": <dynamic_value_from_front_end>},
                    {"format": <dynamic_value_from_front_end>}

                ]}}

Based on the 'dynamic_value_from_front_end', I want to exclude some fields from filter (from $and) query(not from the output but from the 'query') when the 'dynamic_value_from_front_end' is empty.

If I keep '{"size": null}', it searches for where 'size' is 'null' but I totally want to omit {"size": null}' from query. How can I achieve this?

I want some thing like

if size == empty
   {"$match": {"$and": [
                {"height": <dynamic_value_from_front_end>},
                {"format": <dynamic_value_from_front_end>}
   ]}}

if height== empty
   {"$match": {"$and": [
                {"size": <dynamic_value_from_front_end>},
                {"format": <dynamic_value_from_front_end>}
   ]}}

Please guide me how to do this.

Aucun commentaire:

Enregistrer un commentaire