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);
}
});
在这里我可以过滤两个小时之间的数据(例如:17 到 19)。但我需要将数据从 hh:mm && 过滤到 hh:mm(例如:17:15 到 19:30)。
最佳答案
您可以使用$dateToString
运算符来投影格式为 HH:MM
的时间字符串字段,然后您可以在 $match
中进行直接字符串比较。 查询:
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);
}
});
更有效的方法将涉及使用 $redact
的单个管道。 运算符如下:
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);
}
});
关于node.js - 如何从hh :mm to hh:mm in mongoDB过滤两个时间之间的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39868872/