0👍
To directly answer your question, you’ll want to look into using an aggregation pipeline that includes the $group
stage. More specifically, you will probably want to use the $dateTrunc
operator (along with the $dateFromString
operator). You can see an example of this basic approach with your sample data (with a few modified _id
values) in this playground example.
But the limited information in the questions leaves a lot of things unclear. Some additional items for consideration:
- Apart from timespans, how else are you going to be filtering or grouping your data?
- What fields will you be processing when grouping the data together? In the sample playground I simply counted the number of items in each group as it wasn’t clear what the
x
andy
fields were meant to represent. - The only reason that
$dateFromString
is needed currently is due to how thecreatedAt
values are represented in your data. Ideally you should store them as dates not strings, which would remove the need for that extra operator as one benefit.
As a final note, you mention that this is being done to support some charting capabilities. If you are using an Atlas cluster to store this data then you might look into their Charts offering which may help reduce the amount of manual work that you need to do here.
Source:stackexchange.com