Skip to content

Instantly share code, notes, and snippets.

@Ztuu
Created June 29, 2020 07:21
Show Gist options
  • Save Ztuu/adb38ffbe93d5742a392531bf1b5af61 to your computer and use it in GitHub Desktop.
Save Ztuu/adb38ffbe93d5742a392531bf1b5af61 to your computer and use it in GitHub Desktop.
Pymongo: $match on only date portion of datetime Mongodb
import pymongo
from datetime import date
# TODO: Add your connection string, database name and collection name below
my_client = pymongo.MongoClient("...")
my_db = my_client["..."]
my_collection = my_db["..."]
def filter_by_date(query_date):
"""
Filters a mongodb collection on the year, month and day of a date.
As mongodb stores dates as datetimes this allows you to query the date while ignoring the time.
Note: If you expect the count of returned documents to be very high you may prefer to edit this function to
return the mongodb cursor so that it can be iterated over, rather than casting to a list.
"""
date_field = '$my_date_field' #TODO: Update this to the name of the field your date is stored in
return list(my_collection.aggregate([
# TODO: You could add an initial match stage here if there are any other conditions you're filtering on
{
'$project': {
'_id': 1,
'month': {
'$month': date_field
},
'day': {
'$dayOfMonth': date_field
},
'year': {
'$year': date_field
}
# TODO: Project any other fields you need here
}
},
{
'$match': {
'day': query_date.day,
'month': query_date.month,
'year': query_date.year
}
}
]))
# Example of code running
my_date = date.today()
my_filtered_documents = filter_by_date(my_date)
print(len(my_filtered_documents))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment