Here we have a real estate database with 3 houses in it. Each house has a different price. We use find() to get matching houses with prices less than, or greater than, a value.
from pymongo import MongoClient
client = MongoClient(
"mongodb://127.0.0.1:27017")
db = client.real_estate
# Reset.
db.houses.delete_many({})
# Insert houses.
db.houses.insert_many([
{
"address":
"100 Main St.",
"price": 45000},
{
"address":
"110 Main St.",
"price": 50000},
{
"address":
"1400 Rich Ave.",
"price": 200000},
])
# Find inexpensive houses.
print(
"FIND PRICE LT 60000")
cursor = db.houses.find({
"price": {
"$lt": 60000}})
for doc in cursor:
print(doc)
# Find expensive houses.
print(
"FIND PRICE GT 60000")
cursor = db.houses.find({
"price": {
"$gt": 60000}})
for doc in cursor:
print(doc)
FIND PRICE LT 60000
{'address': '100 Main St.',
'_id': ObjectId('59f122302514972194e7e975'), 'price': 45000}
{'address': '110 Main St.',
'_id': ObjectId('59f122302514972194e7e976'), 'price': 50000}
FIND PRICE GT 60000
{'address': '1400 Rich Ave.',
'_id': ObjectId('59f122302514972194e7e977'), 'price': 200000}