Reputation: 859
How do you run a find query using PyMongo to aggregate by month?
I have tried the following:
searchdate = datetime.datetime.now().strftime("%Y-%m-%d")
eventscreated = list(db.event.find({"creator._id":ObjectId(myid)}, {"eventdate": {"$month": 'new Date("'+searchdate+'")'}} ))
results in:
pymongo.errors.OperationFailure: Unsupported projection option: eventdate: { $month: "new Date("2019-09-13")" }
Tried:
isodate = datetime.datetime.now()
isodate = isodate.replace(tzinfo=pytz.utc).isoformat()
eventscreated = list(db.event.find({"creator._id":ObjectId(myid)},
{"eventdate": {"$month": 'ISODate("'+isodate+'")'}} ))
results in:
pymongo.errors.OperationFailure: Unsupported projection option: eventdate: { $month: "ISODate("2019-09-13T07:17:17.222737+00:00")" }
Can anyone help?
Upvotes: 0
Views: 198
Reputation: 859
I managed to find the solution below which gives me what I need:
currmonth = datetime.datetime.now().strftime("%-m")
eventscreated = db.event.aggregate(
[
{"$addFields":
{"month": {"$month": "$eventdate"}}
},
{"$match": {"month": int(currmonth), "creator._id": ObjectId(myid) } }
]
)
Upvotes: 0
Reputation: 8814
You need to use an aggregation pipeline with the $month operator. The snippet creates a test datetime for each day of the year and the aggregation pipeline counts the number of days in each month.
import pymongo
import datetime
db = pymongo.MongoClient()['mydatabase']
# Data setup
db.testdate.delete_many({})
for d in range(0, 365):
dt = datetime.datetime(2019, 1, 1, 12, 0) + datetime.timedelta(days=d)
db.testdate.insert_one({"Testdate": dt})
# Aggregation pipeline
months = db.testdate.aggregate(
[
{"$project":
{"month": {"$month": "$Testdate"}}
},
{"$group":
{"_id": "$month", "count": {"$sum": 1}}
},
{"$sort":
{"_id": 1}
}
]
)
for item in months:
print(item)
Upvotes: 1