Search code examples
pythonmongodbkeyword-argument

Using keyworded args in a function for MongoDB projection


I want to write a flexible function for my Mongo DB that allows me to pass in any number of keys to search for in a collection and return the count of documents. So far I have:

def search_db(**kwargs):

    for k,v in kwargs.items():
        return Mdb['collection1'].find({}, {kwargs[k]:1})

This only allows me to search for one get at a time and iterating over the kwargs kind of defeats the purpose of creating a projection. How can I make it so I can search multiple keys at once?


Solution

  • Using *args

    I do not really get why you use **kwargs here and only use the values, whereas you can use *args:

    def search_db(*args):
        return Mdb['collection1'].find({}, {arg: True for arg in args})
    

    This will thus make a projection with all the arguments you give to search_db, like:

    search_db('field1','field2')
    

    Using **kwargs

    If you really want to use **kwargs, then you can use for example:

    def search_db(**kwargs):
        return Mdb['collection1'].find({}, {arg: True for arg in kwargs.values()})
    

    and call it with:

    search_db(foo='field1',bar='field2')
    

    But here foo and bar as names (not the values), are simply ignored.

    You can use {arg: True for arg in kwargs} if you want to process the parameter names instead.