如何在mongodb中两次过滤数据

的NodeJS

var filter = {}; filter.strBillDate = { "$gte": new Date(req.params.fromdate), "$lt": new Date(req.params.todate) }; Sales.find(filter).exec(function(err, salesdata) { return res.send(salesdata); }); 

这里它会过滤这两天的数据。 我需要每天在这些时间之间过滤数据(即每周7PM到10Pm)

您可以尝试使用聚合框架并利用Date Aggregation Operators来过滤文档。

您需要使用初始的$matchfilter来过滤给定date之间的文档。

然后,您可以使用$projectpipe道创build一个新字段,该字段使用$hour操作符在date字段中保存小时药水。 然后再进行$match来过滤小时范围内的文档。

举个例子,这个例子展示了这个方法,记住了你需要投影你想要返回的字段的聚合框架:

 var filter = {}; filter.strBillDate = { "$gte": new Date(req.params.fromdate), // start of week date "$lt": new Date(req.params.todate) // end of week date }; Sales.aggregate([ { "$match": filter }, { "$project": { "strBillDate": 1, "hourPart": { "$hour": "$strBillDate" }, /* project other fields as necessary */ } }, { "$match": { "hourPart": { "$gte": 19, "$lte": 22 } } } ]).exec(function(err, salesdata) { 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": [ { "$hour": "$strBillDate" }, 19 ] }, { "$lte": [ { "$hour": "$strBillDate" }, 22 ] } ] }, "$$KEEP", "$$PRUNE" ] } } ]).exec(function(err, salesdata) { if (!err) { return res.send(salesdata); } });