I have a set of documents as below:
PropName: 'abc',
TrDates:[{TrDate:367334},{TrDate:367444}]
PropName: 'pqr',
TrDates:[{TrDate:367540},{TrDate:367655}]
PropName: 'xyz',
TrDates:[{TrDate:367550},{TrDate:367650}]
To filter records having at least one element of the TrDates falling into a given rage, I wrote the following in the $match stage of aggregate pipeline which works fine:
[$match: {
TrDates: {
$elemMatch: {
TrDate: {
$gte: 367400,
$lte: 367600
}
}
}
}]
Now I have another requirement to add a new field based on the same condition, i.e: add WithinRange: true to the documents meeting the same condition as above; something like this:
$addFields:{
WithinRange: {$cond: [ { $and: [{$gte: [ "$TrDates.TrDate", 367400 ]}, {$lte: [ "$TrDates.TrDate", 367600 ]}]}, true, false ]}
}
But this doesn’t work. I can use $filter combined with array size checking, but doubt the efficiency. Also I read $elemMatch can be used only within the $match. If that’s the case what’s the most efficient way to do this query?