MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Come filtrare i dati tra due volte da hh:mm a hh:mm in mongoDB

Puoi utilizzare $dateToString operatore per proiettare un campo stringa temporale con il formato HH:MM che puoi quindi eseguire un confronto diretto di stringhe in $match domanda:

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

Un approccio più efficiente implicherebbe un'unica pipeline che utilizza $redact operatore come segue:

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