Home
MongoDB
find, lt and gt Examples
Updated Oct 11, 2023
Dot Net Perls
Find, MongoDB. A real estate database might have a price for each house. We want to find just properties that have a field within a range of values (like a certain price).
With special range queries, used with the find() method, we can find documents with fields in a certain range. The $lt and $gt terms are useful here.
A program. 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.
Note We use the string "$lt" in a nested dictionary argument to find a range of prices less than a value.
Note 2 The "$gt" operator works the same way as less than, but means greater than.
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}
Notes, comparison operators. For small groups of documents, getting all documents and then checking them in an if-statement in Python is possible.
However For large amounts of data, this because impossible. Using MongoDB to query for ranges (with lt and gt) is faster.
A review. Find() can be used with ranges. A dictionary argument with a special term (lt or gt) enables a range query. For large databases, this is essential.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen