Mongodb Query in Python
MongoDB Query in Python
To query a MongoDB database using Python, you use the find() and find_one() methods from the pymongo library.
1. Install pymongo
Before you start querying MongoDB, ensure that you have the pymongo library installed:
pip install pymongo2. Connect to MongoDB
Before running queries, establish a connection to your MongoDB instance.
import pymongo# Connect to MongoDBclient = pymongo.MongoClient("mongodb://localhost:27017/")# Select the databasedb = client["mydatabase"]# Select the collectioncollection = db["mycollection"]3. Querying MongoDB
MongoDB queries in Python use the find() and find_one() methods.
a) Find One Document (find_one())
The find_one() method returns the first document that matches the query.
# Find one document (first record in the collection)document = collection.find_one()print(document)Find One with a Condition
You can specify a condition to find a specific document.
document = collection.find_one({"name": "Alice"})print(document)This will return the first document where the name is "Alice".
b) Find Multiple Documents (find())
The find() method returns all documents that match the query.
# Find all documents in the collectiondocuments = collection.find()# Loop through the documents and print themfor doc in documents: print(doc)Find Documents with a Condition
You can filter results by passing a query.
query = {"age": {"$gt": 25}} # Find people with age greater than 25documents = collection.find(query)for doc in documents: print(doc)| MongoDB Query Operators | Description | Example Query |
|---|---|---|
$eq | Equal to | {"age": {"$eq": 30}} |
$ne | Not equal to | {"age": {"$ne": 30}} |
$gt | Greater than | {"age": {"$gt": 25}} |
$gte | Greater than or equal to | {"age": {"$gte": 25}} |
$lt | Less than | {"age": {"$lt": 40}} |
$lte | Less than or equal to | {"age": {"$lte": 40}} |
$in | Match any value in a list | {"city": {"$in": ["New York", "Los Angeles"]}} |
$nin | Match values not in a list | {"city": {"$nin": ["Chicago", "Houston"]}} |
4. Using Projections (Selecting Specific Fields)
By default, find() returns all fields in a document. You can use projections to return only specific fields.
# Retrieve only 'name' and 'city', exclude '_id'documents = collection.find({}, {"_id": 0, "name": 1, "city": 1})for doc in documents: print(doc)In this example:
{"_id": 0}excludes the_idfield.{"name": 1, "city": 1}includes only thenameandcityfields.
5. Sorting Results
You can use the sort() method to sort the query results.
# Sort documents by age in ascending orderdocuments = collection.find().sort("age", pymongo.ASCENDING)for doc in documents: print(doc)To sort in descending order, use pymongo.DESCENDING.
documents = collection.find().sort("age", pymongo.DESCENDING)for doc in documents: print(doc)6. Limit and Skip (Pagination)
To limit the number of results returned, use limit().
# Retrieve only 3 documentsdocuments = collection.find().limit(3)for doc in documents: print(doc)To skip a certain number of documents, use skip().
# Skip the first 2 documents and get the next 3documents = collection.find().skip(2).limit(3)for doc in documents: print(doc)7. Querying with AND, OR, and NOT
You can use logical operators like $and, $or, and $not to combine conditions.
Using $and
query = { "$and": [ {"age": {"$gt": 25}}, {"city": "New York"} ]}documents = collection.find(query)for doc in documents: print(doc)Using $or
query = { "$or": [ {"age": {"$gt": 30}}, {"city": "Los Angeles"} ]}documents = collection.find(query)for doc in documents: print(doc)Using $not
query = {"age": {"$not": {"$gte": 30}}} # Find people younger than 30documents = collection.find(query)for doc in documents: print(doc)8. Closing the Connection
After completing the queries, close the MongoDB connection.
client.close()Conclusion
| Method | Description |
|---|---|
find_one() | Returns the first document that matches the query |
find() | Returns multiple documents that match the query |
limit(n) | Limits the number of documents returned |
skip(n) | Skips a specified number of documents |
sort(field, order) | Sorts results based on a field |
projection | Selects specific fields to return |
These methods help you efficiently query and filter data from MongoDB using Python. ?