How to Exclude Specified Field Using Find() Method in Python


In this example we will show how to exclude the specified field using the find() method in Python MongoDB.

Source Code

from pymongo import MongoClient

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

# exclude "Abbreviation" from the result
for x in collection.find({}, {"Abbreviation": 0}):
    print(x)

Output:

{'_id': 1, 'State_name': 'Alabama', 'Capital': 'Montgomery', 'Total_area': 52420}
{'_id': 2, 'State_name': 'Alaska', 'Capital': 'Juneau', 'Total_area': 665384}
{'_id': 3, 'State_name': 'Arizona', 'Capital': 'Phoenix', 'Total_area': 113990}
{'_id': 4, 'State_name': 'Arkansas', 'Capital': 'Little Rock', 'Total_area': 53179}
{'_id': 5, 'State_name': 'California', 'Capital': 'Sacramento', 'Total_area': 163695}
{'_id': 6, 'State_name': 'Colorado', 'Capital': 'Denver', 'Total_area': 104094}
{'_id': 7, 'State_name': 'Connecticut', 'Capital': 'Hartford', 'Total_area': 5543}
{'_id': 8, 'State_name': 'Delaware', 'Capital': 'Dover', 'Total_area': 2489}
{'_id': 9, 'State_name': 'Florida', 'Capital': 'Tallahassee', 'Total_area': 65758}
{'_id': 10, 'State_name': 'Georgia', 'Capital': 'Atlanta', 'Total_area': 59425}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments