如何在mongoDB中从hh:mm到hh:mm两次过滤数据

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的时间string字段,然后您可以在$match查询中直接进行string比较:

 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操作符的单个pipe道,如下所示:

 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); } });