Nivin Nivin - 1 month ago 7
Node.js Question

How to filter data between two times in 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);
});


Here It will filter data bewtween these two days. I need to filter the data between these times everyday.(ie 7PM to 10Pm in a week)

Answer

You could try using the aggregation framework and take advantage of the Date Aggregation Operators in filtering your documents.

You'd need an initial $match filter to filter the documents between the given days.

You can then use a $project pipeline to create a new field that holds the hour potion on the date field using the $hour operator. A further $match would then be applied to filter the documents on the hour range.

Take for instance this example which shows this approach, bearing in mind with the aggregation framework you'd need to project the fields you want to return:

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

A more efficient approach would involve a single pipeline that uses the $redact operator as follows:

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