Query Mongodb on month, day, year... of a datetime

Query Mongodb on month, day, year... of a datetime

You can query MongoDB on the month, day, and year components of a datetime field using the aggregation framework and the $month, $dayOfMonth, and $year aggregation operators. Here's an example of how to do this:

Assuming you have a collection named "events" with documents containing a datetime field called "event_date," you can query for documents with specific month, day, and year components as follows:

from pymongo import MongoClient # Connect to the MongoDB server client = MongoClient('mongodb://localhost:27017/') # Access your database and collection db = client['your_database_name'] collection = db['events'] # Define the target month, day, and year target_month = 9 target_day = 28 target_year = 2023 # Create an aggregation pipeline to match documents pipeline = [ { '$match': { '$expr': { '$and': [ {'$eq': [{'$month': '$event_date'}, target_month]}, {'$eq': [{'$dayOfMonth': '$event_date'}, target_day]}, {'$eq': [{'$year': '$event_date'}, target_year]} ] } } } ] # Execute the aggregation pipeline and retrieve the results result = list(collection.aggregate(pipeline)) # Print the matching documents for doc in result: print(doc) 

In this code:

  • We connect to the MongoDB server and access the desired database and collection.

  • We define the target month, day, and year that you want to query.

  • We create an aggregation pipeline that uses the $match stage with the $expr operator to perform a logical "and" operation on the $month, $dayOfMonth, and $year operators to match documents with the specified date components.

  • We execute the aggregation pipeline using collection.aggregate(pipeline) and retrieve the matching documents.

  • Finally, we print the matching documents.

Replace 'your_database_name' with the name of your MongoDB database and adjust the target_month, target_day, and target_year variables to specify the date components you want to query.

Examples

  1. "MongoDB query by specific year"

    • Query documents based on a specific year from a datetime field.
    from pymongo import MongoClient from datetime import datetime client = MongoClient("mongodb://localhost:27017/") db = client.my_database year = 2022 results = db.my_collection.find({"my_date_field": {"$gte": datetime(year, 1, 1), "$lt": datetime(year + 1, 1, 1)}}) for result in results: print(result) 
  2. "MongoDB query by specific month"

    • Query documents based on a specific month of a datetime field.
    from pymongo import MongoClient from datetime import datetime client = MongoClient("mongodb://localhost:27017/") db = client.my_database year = 2022 month = 3 # March results = db.my_collection.find({"my_date_field": {"$gte": datetime(year, month, 1), "$lt": datetime(year, month + 1, 1)}}) for result in results: print(result) 
  3. "MongoDB query by specific day"

    • Query documents based on a specific day from a datetime field.
    from pymongo import MongoClient from datetime import datetime, timedelta client = MongoClient("mongodb://localhost:27017/") db = client.my_database year = 2022 month = 3 day = 15 start_date = datetime(year, month, day) end_date = start_date + timedelta(days=1) results = db.my_collection.find({"my_date_field": {"$gte": start_date, "$lt": end_date}}) for result in results: print(result) 
  4. "MongoDB query by specific date range"

    • Query documents within a specific date range.
    from pymongo import MongoClient from datetime import datetime client = MongoClient("mongodb://localhost:27017/") db = client.my_database start_date = datetime(2022, 1, 1) end_date = datetime(2022, 12, 31) results = db.my_collection.find({"my_date_field": {"$gte": start_date, "$lt": end_date}}) for result in results: print(result) 
  5. "MongoDB query by specific weekday"

    • Query documents where a datetime field matches a specific weekday.
    from pymongo import MongoClient from datetime import datetime client = MongoClient("mongodb://localhost:27017/") db = client.my_database # 0 = Monday, 6 = Sunday weekday = 2 # Wednesday results = db.my_collection.find({ "$expr": { "$eq": [{"$dayOfWeek": "$my_date_field"}, weekday + 1] # MongoDB dayOfWeek: 1 (Sunday), 7 (Saturday) } }) for result in results: print(result) 
  6. "MongoDB query by specific time"

    • Query documents where a datetime field matches a specific time of day.
    from pymongo import MongoClient from datetime import datetime client = MongoClient("mongodb://localhost:27017/") db = client.my_database start_time = datetime(2022, 1, 1, 9, 0, 0) # 9 AM end_time = datetime(2022, 1, 1, 10, 0, 0) # 10 AM results = db.my_collection.find({ "$expr": { "$and": [ {"$gte": [{"$hour": "$my_date_field"}, start_time.hour]}, {"$lt": [{"$hour": "$my_date_field"}, end_time.hour]} ] } }) for result in results: print(result) 
  7. "MongoDB query with datetime comparison"

    • Query documents with a datetime field matching a specific condition.
    from pymongo import MongoClient from datetime import datetime client = MongoClient("mongodb://localhost:27017/") db = client.my_database specific_date = datetime(2022, 3, 15) results = db.my_collection.find({"my_date_field": {"$eq": specific_date}}) for result in results: print(result) 
  8. "MongoDB query by specific month and year"

    • Query documents where a datetime field matches a specific month and year.
    from pymongo import MongoClient from datetime import datetime client = MongoClient("mongodb://localhost:27017/") db = client.my_database year = 2022 month = 3 results = db.my_collection.find({ "$expr": { "$and": [ {"$eq": [{"$year": "$my_date_field"}, year]}, {"$eq": [{"$month": "$my_date_field"}, month]} ] } }) for result in results: print(result) 
  9. "MongoDB query by day and month"

    • Query documents where a datetime field matches a specific day and month.
    from pymongo import MongoClient from datetime import datetime client = MongoClient("mongodb://localhost:27017/") db = client.my_database month = 3 day = 15 results = db.my_collection.find({ "$expr": { "$and": [ {"$eq": [{"$month": "$my_date_field"}, month]}, {"$eq": [{"$dayOfMonth": "$my_date_field"}, day]} ] } }) for result in results: print(result) 
  10. "MongoDB query by hour of the day"


More Tags

arraylist microtime plc uicollectionviewcell resteasy rider admin-on-rest angularjs-ng-click 3d game-physics

More Python Questions

More Stoichiometry Calculators

More Date and Time Calculators

More Organic chemistry Calculators

More Dog Calculators