[Python] Query a Mongdb collection for documents which contain a dictionary of specific keys

Discussão em 'Python' iniciado por Stack, Janeiro 20, 2025.

  1. Stack

    Stack Membro Participativo

    How does one query a DictField to see if the keys contain a specific string. Originally the dictionary was used as it was easier to query or elements further in the tree. However, when expanding I found that some of the entries would most likely contain multiples of the same dictionary item. As such I introduced an increment but now need to change the querying.

    the structure of the document currently looks like this

    {"_id": "ffgame",
    "game": "Final Fantasy"
    "media": {
    "image_1":{"title": "red mage",
    "file_size": 2045432},
    "movie_1":{"title": "characters dancing",
    "file_size": 2045432},
    "image_2":{"title": "blue mage",
    "file_size": 2045432},
    "image_3":{"title": "red mage",
    "file_size": 8675309},
    }
    },
    {"_id": "ff2game",
    "game": "Final Fantasy 2"
    "media": {
    "image_1":{"title": "red mage",
    "file_size": 8008135},
    }
    }


    My original code for querying is as follows. If I wanted to find images with the red mage, the query is simple and straight forward.

    I am using Mongoengine as the entry point into mongodb.

    search_term = "red mage"
    file_type = "image"

    query = Q(**{f"media.{file_type}.title": search_term})
    found_documents = GameDocument.objects(query)


    but as the file_type is now increments to account for more than one image this no longer works.

    Continue reading...

Compartilhe esta Página