Home > OS >  MongoDB extract specific value python
MongoDB extract specific value python

Time:11-28

I want to extract value of name :

x = col.find({},{'_id': 0, 'country.name': 1})
 
for data in x:
    #if data == 'India':
        print(data['country'])

This above code generate this output:

{'name': 'India'}
{'name': 'Colombia'}
{'name': 'Iran (Islamic Republic of)'}
{'name': 'Germany'}

Desire output: India Colombia Iran (Islamic Republic of) Germany

In mongodb every entris have id but name of country is subarray of array

CodePudding user response:

We need to create a list and append country name in that, and use join outside the for loop, It will print the expected output.

countries = []
for data in x:
    countries.append(data.get("country", {}).get("name"))
print("Output: ", " ".join(countries))
  • Related