问题
Mongoose
var filter = {};
filter.strBillDate = {
"$gte": new Date(req.params.fromdate),
"$lt": new Date(req.params.todate)
};
return Sales
.aggregate([{
$match: filter
}, {
"$project": {
"strBillNumber": 1,
"strBillAmt": 1,
"store_id": 1,
"strBillDate": 1,
"hourPart": {
"$hour": "$strBillDate"
},
"minutePart": {
"$minute": "$strBillDate"
},
}
}, {
"$match":
{ "hourPart": { "$gte": fromhour, "$lte": tohour } }
}])
.exec(function(err, salesdata) {
if (!err) {
return res.send(salesdata);
}
});
Here I can filter data between two hours(Ex: 17 to 19). But I need to filter that data from hh:mm && to hh:mm(Eg: 17:15 to 19:30).
回答1:
You could use the $dateToString operator to project a time string field with the format HH:MM
that you can then do a direct string comparison in the $match query:
var filter = {};
filter.strBillDate = {
"$gte": new Date(req.params.fromdate),
"$lt": new Date(req.params.todate)
};
return Sales
.aggregate([{
$match: filter
}, {
"$project": {
"strBillNumber": 1,
"strBillAmt": 1,
"store_id": 1,
"strBillDate": 1,
"time": { "$dateToString": { "format": "%H:%M", date: "$strBillDate" } }
}
}, {
"$match":
{ "time": { "$gte": "17:15", "$lte": "19:30" } }
}])
.exec(function(err, salesdata) {
if (!err) {
return res.send(salesdata);
}
});
A more efficient approach would involve a single pipeline that uses the $redact operator as follows:
Sales.aggregate([
{
"$redact": {
"$cond": [
{
"$and": [
{ "$gte": [ "$strBillDate", new Date(req.params.fromdate) ] },
{ "$lt": [ "$strBillDate", new Date(req.params.todate) ] },
{
"$gte": [
{
"$dateToString": {
"format": "%H:%M",
"date": "$strBillDate"
}
},
"17:15"
]
},
{
"$lte": [
{
"$dateToString": {
"format": "%H:%M",
"date": "$strBillDate"
}
},
"19:30"
]
}
]
},
"$$KEEP",
"$$PRUNE"
]
}
}
]).exec(function(err, salesdata) {
if (!err) {
return res.send(salesdata);
}
});
来源:https://stackoverflow.com/questions/39868872/how-to-filter-data-between-two-times-from-hhmm-to-hhmm-in-mongodb