Search code examples
pythondatabasepymongo

Assigning mongodb array element in a variable in pymongo


i am making a self-project for practice but i am stuck at a point. I am not able to store the value of an element of an array of mongodb in a variable.

server = pymongo.MongoClient(url)
pokemon_python = server.pokemon_python
gonestarter = pokemon_python.gonestarter


bulba_health = gonestarter.find_one({"stats":{"$elemMatch":{"health": 15}}}, {"stats":{"$elemMatch":{"health": 15}}})


bulba_health = str(bulba_health["stats"])
print(f"Health: {bulba_health}")

the result is printed as Health: [{'health': 15}]

but the result i want is that only gives me Health: 15


Solution

  • Given your current python code, you can access the value you want with:

    bulba_health["stats"][0]["health"]
    

    bulba_health["stats"] retrieves the array values of the "stats" field:

    [{"health": 15}, ...]
    

    bulba_health["stats"][0] retrieves the first element in the array:

    {"health": 15}
    

    bulba_health["stats"][0]["health"] retrieves the value of the "health" field:

    15