1

I have this Json inside mongodb

{
"_id" : ObjectId("5aba203f00435837802f9c49"),
"AED" : 4.572098,
"AFN" : 86.093419,
"ALL" : 130.478529,
"AMD" : 597.524404,
"ANG" : 2.216574,
"AOA" : 264.413246,
}

And this in Python

import pymongo
uri = "mongodb://127.0.0.1:27017"
client= pymongo.MongoClient(uri)
database = client['countries_db']
collection = database['currency']

currency =[AED['AED'] for AED in collection.find({})]
res=currency*2
print(res)

Output: [4.572098, 4.572098]

And when I print this, It comes as a string value, It repeats AED two times. Is there any way to call the value as float and calculate it? Thanks.

1 Answer 1

2

The problem isn't that it's returning a string value; it's returning a list. When you try to multiply a list, it'll just duplicate itself that many times, which is what you're seeing here. How you resolve it depends on how many elements you expect to get back from the find() operation as well as what you'd like to do with them all.

  1. If you're expecting 1 element as a result of the find() operation, you should turn that into a find_one(), which will return a float, making your multiplication operation work as expected with the following code:

    item = collection.find_one({})  # Returns a single doc. Note the lack of square brackets
    currency = item['AED']  # Get the desired key of the document
    res = currency * 2
    
  2. If you're expecting more than 1 element, you can multiple each returned value by 2 by running a map on it with res = map(lambda x: x*2, currency)

Sign up to request clarification or add additional context in comments.

2 Comments

I just have to import one element, it didn't work, I want the element that is inside the object, do I have to import the object in Mongo?
See the changes to my response. You still needed to remove the square brackets wrapping the call, which was creating a list (in addition to the call to find(), which was also returning a list).

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.