I am getting values a,b from user through an HTML form and passing it to the below query. My requirement is to retrieve document based on the a & b values and in case they are empty I need to retrieve all the doucments. Can someone help me with the query, please? What should I pass instead of search_data["a"] & search_data["b"] to get all the documents?
query = user_collection.aggregate([
{
"$project": {
"_id": 0
}
},
{
"$match": {
"a": search_data['a'],
"b": search_data['b'],
}
}
])
If you are only doing a match and project, you don't need an aggregate query, you can use the much simpler
find()
operation.The code below will take your
search_data
dict and using dict comprehension, create asearch_filter
that only filters on the keys that have some data in (e.g.) removes nulls (None
) and empty (''
) fields. It's a nicer solution as you can add more fields without having to change the code.Full worked example:
gives: