I’m assuming you’re having an error, but you don’t state what that was. Based on playing around with the code you posted above I was getting the following error:
MongoServerError: PlanExecutor error during aggregation :: caused by :: $dateAdd requires startDate to be convertible to a date
If that’s what you’re running into, I was able to resolve that by $unwinding the audiences array. It seem like the array is causing issues in the $dateAdd call.
If you’re having other issues let us know what they are so we can more quickly help you out.
In my mongodb collection, startDate is a date.
Here’s the message error in my case:
{
"message" : "unknown top level operator: $$NOW. If you have a field name that starts with a '$' symbol, consider using $getField or $setField.",
"ok" : 0,
"code" : 2,
"codeName" : "BadValue",
"$clusterTime" : {
"clusterTime" : Timestamp(1660636531, 8),
"signature" : {
"hash" : "TglED2lvQswahQMyU5G7aIEsQBA=",
"keyId" : NumberLong("7067609856571604994")
}
},
"operationTime" : Timestamp(1660636531, 8)
}
If you look at the documentation of $addDate you will see that both startDate and amount requires an <expression>. As such to access your field values you need to use the dollar sign. So it should be
startDate: "$audiences.startDate"
rather than
startDate: "audiences.startDate"
The syntax for $match is
fieldName : ValueOrComparator
The $$NOW variable is not a field name. I am not too sure about this one but I think you need to be inside $expr to be able to use it.