How to Get All Documents Containing Specified Fields in Python


In this example we will show how to get all documents containing the specified fields in the collection using the find() method in Python MongoDB.

Source Code

from pymongo import MongoClient

client = MongoClient("localhost", 27017)
db = client["mydatabase"]
collection = db["us_state"]

# get only the State_names, Abbreviations, Capitals, Total_areas, not the _ids
for x in collection.find({}, {"_id": 0, "State_name": 1, "Abbreviation": 1, "Capital": 1, "Total_area": 1}):
    print(x)

Output:

{'State_name': 'Alabama', 'Abbreviation': 'AL', 'Capital': 'Montgomery', 'Total_area': 52420}
{'State_name': 'Alaska', 'Abbreviation': 'AK', 'Capital': 'Juneau', 'Total_area': 665384}
{'State_name': 'Arizona', 'Abbreviation': 'AZ', 'Capital': 'Phoenix', 'Total_area': 113990}
{'State_name': 'Arkansas', 'Abbreviation': 'AR', 'Capital': 'Little Rock', 'Total_area': 53179}
{'State_name': 'California', 'Abbreviation': 'CA', 'Capital': 'Sacramento', 'Total_area': 163695}
{'State_name': 'Colorado', 'Abbreviation': 'CO', 'Capital': 'Denver', 'Total_area': 104094}
{'State_name': 'Connecticut', 'Abbreviation': 'CT', 'Capital': 'Hartford', 'Total_area': 5543}
{'State_name': 'Delaware', 'Abbreviation': 'DE', 'Capital': 'Dover', 'Total_area': 2489}
{'State_name': 'Florida', 'Abbreviation': 'FL', 'Capital': 'Tallahassee', 'Total_area': 65758}
{'State_name': 'Georgia', 'Abbreviation': 'GA', 'Capital': 'Atlanta', 'Total_area': 59425}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments