如何在mongodb中两次过滤数据

时间:2016-10-03 10:15:57

标签: node.js mongodb mongoose mongodb-query aggregation-framework

的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)

1 个答案:

答案 0 :(得分: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);
    }
});