Ok, i try to explain my aim.
My Input is:{"_id":{"$oid":"624d987e1924b4a722dbbd5f"}, "fruit_type":"banana", "sale_date": [{"date":{"$date":"2022-01-12T00:00:00.000Z"}},{"date":{"$date":"2022-01-13T00:00:00.000Z"}}, {"date":{"$date":"2022-01-14T00:00:00.000Z"}},{"date":{"$date":"2022-01-14T00:00:00.000Z"}}, {"date":{"$date":"2022-01-15T00:00:00.000Z"}},{"date":{"$date":"2022-02-12T00:00:00.000Z"}}, {"date":{"$date":"2022-02-13T00:00:00.000Z"}},{"date":{"$date":"2022-02-14T00:00:00.000Z"}}, {"date":{"$date":"2022-02-15T00:00:00.000Z"}},{"date":{"$date":"2021-01-12T00:00:00.000Z"}}, {"date":{"$date":"2021-01-13T00:00:00.000Z"}},{"date":{"$date":"2021-01-14T00:00:00.000Z"}}, {"date":{"$date":"2021-01-15T00:00:00.000Z"}}]}
and it represents every day that I have sold a banana.
Now i want to know if between two dates i have sold a banana, so if my two dates are 2021-01-15
and 2021-01-20
, (i use this dates for an easy example, but in reality the dates can differ both by months and by years), and i want to know how many bananas i have sold (If a day i have sold two bananas in the array sale_date i have two object date with the same value).
How solutions i’m using this process:
1)set the dates:
[{$set: {
startDate: ISODate('2022-01-13T00:00:00.000Z'),
endDate: ISODate('2022-01-17T00:00:00.000Z')
}},
- I create my dates array with alla day between startDate and endDate. In this point i have my first problem, because if i have two dates in the same month it’s woks, but with different months or years it doesn’t works: (solution by @Asya_Kamsky )
$set: {
dates: {
$map: {
input: {
$range: [
0,
{
$subtract: [{
$add: [
1,
'$endDate'
]
},
'$startDate'
]
},
1000*60*60*24
]
},
'in': {
$add: [
'$startDate',
'$$this'
]
}
}
}
}
}
- Now I filter the sale_date array with only the date that are between startDate and endDate:
{
$project: {
_id: 1,
fruit_type: 1,
startDate: 1,
endDate: 1,
sale_date: {
$filter: {
input: '$sale_date',
as: 'info_sales',
cond: {
$and: [{
$gte: [
'$$info_sales.date',
'$startDate'
]
},
{
$lt: [
'$$info_sales.date',
'$endDate'
]
}
]
}
}
},
dates: 1
}
}
- I make the unwind of dates.
{
$unwind: {
path: '$dates'
}
}
4.1) So, to sum up now my documents is like this, i have one document for every days between startDate and endDate
fruit_type:"banana"
startDate:2022-01-13T00:00:00.000+00:00
endDate:2022-01-17T00:00:00.000+00:00
dates:2022-01-13T00:00:00.000+00:00
sale_date:Array
date:2022-01-13T00:00:00.000+00:00
...(other date)
- At this point i’m blocked. How can i check if value
dates
exist in sale_date
and than found how many bananas i have sold that day?
Thank you soooooo much.