How to retrieve all documents with the $match query in MongoDB Atlas

653 Views Asked by At

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'],

            }
        }

    ])
1

There are 1 best solutions below

0
On BEST ANSWER

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 a search_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.

search_filter = {k: v for (k, v) in search_data.items() if not (v is None or v == '')}
query = user_collection.find(search_filter, {'_id': 0})

Full worked example:

from pymongo import MongoClient

db = MongoClient()['mydatabase']
user_collection = db.user_collection


def filtered_query(search_data):
    search_filter = {k: v for (k, v) in search_data.items() if not (v is None or v == '')}
    print(search_filter)  # Just to show what it is doing
    return user_collection.find(search_filter, {'_id': 0})

# Test it out!

filtered_query({'a': 1, 'b': ''})
filtered_query({'a': None, 'b': 3, 'c': 'x'})
filtered_query({'a': 'x123', 'b': 3, 'c': 'x', 'd': None, 'e': '', 'f': 'f'})

gives:

{'a': 1}
{'b': 3, 'c': 'x'}
{'a': 'x123', 'b': 3, 'c': 'x', 'f': 'f'}