1

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

2
  • Does bulba_health["stats"][0]["health"] get the value you want? Commented Nov 5, 2022 at 2:43
  • 1
    Thanks @rickhg12hs this worked i was stuck on this problem since yesterday.....Thank you for helping out Commented Nov 5, 2022 at 3:38

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.