Ik heb het zelf:
db.bills.aggregate([
{
$match: {
$expr: {
$or: [
{
$and: [
{$eq: ["$year", FROMYEAR]},
{$eq: ["$year", TOYEAR]},
{$gte: ["$month", FROMMONTH},
{$lte: ["$month", TOMONTH},
]
},
{
$and: [
{$eq: ["$year", FROMYEAR]},
{$lt: ["$year", TOYEAR]},
{$gte: ["$month", FROMMONTH]}
]
},
{
$and: [
{$gt: ["$year", FROMYEAR]},
{$eq: ["$year", TOYEAR]},
{$lte: ["$month", TOMONTH]}
]
},
{
$and: [
{$gt: ["$year", FROMYEAR]},
{$lt: ["$year", TOYEAR]}
]
}
]
}
}
},
{
$project: {
"id": 1,
"month": 1,
"year": 1,
"_id": 0
}
},
,
{
$sort: {
"year": 1,
"month": 1
}
}
]).toArray()
De eerste is om fromYear, fromMonth, toYear, toMonth uit de query te extraheren. De volgende is om het in te stellen op de overeenkomstige positie in de zoekopdracht. Er zijn 4 bereiken die overeenkomen:
MinYear = $year = MaxYear ==========> MinMonth < $month < MaxMonth
MinYear = $year < MaxYear ==========> MinMonth <= $month
MinYear < $year = MaxYear ==========> $month <= MaxMonth
MinYear < $year < MaxYear ==========> any $month
Het resultaat ziet er als volgt uit:
[
{
"id" : "BI_0010",
"month" : 5,
"year" : 2017
},
{
"id" : "BI_0008",
"month" : 3,
"year" : 2018
},
{
"id" : "BI_0001",
"month" : 8,
"year" : 2018
}
]