How to Specify Advanced Query Conditions by Using Modifiers in Python


In this example we will show how to specify advanced query conditions when using the find() method by using modifiers in Python MongoDB.

Source Code

from pymongo import MongoClient

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

# find the documents where the "Capital" field starts with the letter less than the letter "H" (alphabetically)
query = {"Capital": {"$lt": "H"}}

for x in collection.find(query):
    print(x)

Output:

{'_id': 6, 'State_name': 'Colorado', 'Abbreviation': 'CO', 'Capital': 'Denver', 'Total_area': 104094}
{'_id': 8, 'State_name': 'Delaware', 'Abbreviation': 'DE', 'Capital': 'Dover', 'Total_area': 2489}
{'_id': 10, 'State_name': 'Georgia', 'Abbreviation': 'GA', 'Capital': 'Atlanta', 'Total_area': 59425}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments