Jeg fik det selv:
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()
Den første er at udtrække fromYear, fromMonth, toYear, toMonth fra forespørgsel. Det næste er at sætte det til den tilsvarende position i forespørgslen. Der er 4 intervaller, der skal matche:
MinYear = $year = MaxYear ==========> MinMonth < $month < MaxMonth
MinYear = $year < MaxYear ==========> MinMonth <= $month
MinYear < $year = MaxYear ==========> $month <= MaxMonth
MinYear < $year < MaxYear ==========> any $month
Resultatet ser således ud:
[
{
"id" : "BI_0010",
"month" : 5,
"year" : 2017
},
{
"id" : "BI_0008",
"month" : 3,
"year" : 2018
},
{
"id" : "BI_0001",
"month" : 8,
"year" : 2018
}
]