1

的NodeJS如何在MongoDB中過濾兩次之間的數據

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

這裏它會過濾bewtween這兩天的數據。我需要每天在這些時間之間過濾數據(即每週7PM到10Pm)

回答

1

您可以嘗試使用聚合框架並利用Date Aggregation Operators來過濾文檔。

您需要一個初始的$match過濾器來過濾給定日期之間的文檔。

然後,您可以使用$project管道創建包含關於使用$hour操作日期字段小時藥水的新領域。然後將應用另一個$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運算符的單個流水線如下:

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); 
    } 
}); 
相關問題