Python MongoDB - Query
MongoDB queries let you filter documents(records) using conditions. The find() method retrieves documents from a collection, and you can pass an optional query to specify which documents to return.
A query is pass as a parameter to filter the results. This query uses key-value pairs and various operators.
Collection.find(query)
- query is optional. If no query is provided, it returns all documents in the collection.
Common MongoDB Query Operators
Following is the list of some operators used in the queries in MongoDB:
Operation | Syntax | Description |
---|---|---|
Equality | {"key" : "value"} | Matches documents with exact value. |
Less Than | { "key" : {$lt:"value"} } | Matches values less than the given value. |
Greater Than | { "key" : {$gt:"value"} } | Matches values greater than the given value. |
Less Than Equal to | { "key" : {$lte:"value"} } | Matches values less than or equal to the value. |
Greater Than Equal to | { "key" : {$gte:"value"} } | Matches values greater than or equal to the value. |
Not Equal to | { "key" : {$ne: "value"} } | Matches all values not equal to the given value. |
Logical AND | { "$and" : [ {exp1}, {exp2},..., {expN} ] } | Returns documents that match all conditions. |
Logical OR | { "$or" : [ {exp1}, {exp2},..., {expN} ] } | Returns documents that match at least one condition. |
Logical NOT | { "$not" : [ {exp1}, {exp2},..., {expN} ] } | Inverts the condition. |
Sample Collection used in this article:
Example 1:
This example filters and displays documents from the collection based on the Quantity field, the first query shows documents with Quantity greater than 40, while the second shows those with Quantity less than 40.
from pymongo import MongoClien
client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["GeeksForGeeks"]
cursor = collection.find({"Quantity": {"$gt": 40}})
print("The data having Quantity greater than 40 is:")
for doc in cursor:
print(doc)
cursor = collection.find({"Quantity": {"$lt": 40}})
print("\nThe data having Quantity less than 40 is:")
for doc in cursor:
print(doc)
Output
Example 2:
It demonstrates the use of logical operators in MongoDB queries, the first query uses $and to retrieve documents where Quantity satisfies both conditions and the second uses $or to fetch documents where Quantity meets at least one condition.
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
collection = db["GeeksForGeeks"]
cursor = collection.find({"$and": [{"Quantity": {"$gt": 40}}, {"Quantity": {"$gt": 50}}] })
print("\nQuantities greater than 40 AND Quantities greater than 40:")
for doc in cursor:
print(doc)
cursor = collection.find({"$or": [{"Quantity": {"$gt": 40}}, {"Quantity": {"$gt": 50}}] })
print("\nQuantities greater than 40 OR Quantities greater than 40:")
for doc in cursor:
print(doc)
Output
Related Articles: