Je l'ai eu moi-même :
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()
La première consiste à extraire fromYear, fromMonth, toYear, toMonth de la requête. La prochaine consiste à le définir à la position correspondante dans la requête. Il y a 4 plages à faire correspondre :
MinYear = $year = MaxYear ==========> MinMonth < $month < MaxMonth
MinYear = $year < MaxYear ==========> MinMonth <= $month
MinYear < $year = MaxYear ==========> $month <= MaxMonth
MinYear < $year < MaxYear ==========> any $month
Le résultat ressemble à ceci :
[
{
"id" : "BI_0010",
"month" : 5,
"year" : 2017
},
{
"id" : "BI_0008",
"month" : 3,
"year" : 2018
},
{
"id" : "BI_0001",
"month" : 8,
"year" : 2018
}
]