Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb aggregate to get data in between 2 dates

let params = JSON.parse(req.query.params);
let dateFrom = params.dateFrom;
let dateTo = params.dateTo;
dateFrom = dateFrom.replace(/T/g, ' '); //parse the data to the format accepted by mongodb
dateFrom = dateFrom.replace(/Z/g, ' ');
dateTo = dateTo.replace(/T/g, ' ');
dateTo = dateTo.replace(/Z/g, ' ');



productSchema.aggregate([
    {
        $match: { 
            productExist: true,
        }
    },
    {
        $match: { 
            productTimeStamp: {
                $gte: dateTo,
                $lte: dateFrom
            } 
        }
    },        
    { 
        $lookup:
            {
                from: 'supplierschemas',
                localField: 'supplierId',
                foreignField: '_id',
                as: 'supplier'
            }
    },
    { 
        $lookup:
            {
                from: 'brandschemas',
                localField: 'brandId',
                foreignField: '_id',
                as: 'brand'
            }
    },
    { 
        $lookup:
            {
                from: 'categoryschemas',
                localField: 'categoryId',
                foreignField: '_id',
                as: 'category'
            }
    })]

I have the query above that gets data from mongodb using express. I want to select the 2 dates in between. But the code above is not working when I added these lines of codes:

    {
        $match: { 
            productTimeStamp: {
                $gte: dateTo,
                $lte: dateFrom
            } 
        }
    }, 

How excactly I can add these statement to get the data from 2 dates?

like image 323
C.E James Avatar asked Oct 21 '18 02:10

C.E James


Video Answer


1 Answers

MongoDB default date is ISODate. Do not do replace on the dates.

Instead just pass them as new Dates:

let params = JSON.parse(req.query.params);

productSchema.aggregate([{
    $match: {
      productExist: true,
    }
  },
  {
    $match: {
      productTimeStamp: {
        $gte: new Date(params.dateFrom),
        $lte: new Date(params.dateTo)
      }
    }
  },
  {
    $lookup: {
      from: 'supplierschemas',
      localField: 'supplierId',
      foreignField: '_id',
      as: 'supplier'
    }
  },
  {
    $lookup: {
      from: 'brandschemas',
      localField: 'brandId',
      foreignField: '_id',
      as: 'brand'
    }
  },
  {
    $lookup: {
      from: 'categoryschemas',
      localField: 'categoryId',
      foreignField: '_id',
      as: 'category'
    }
  })]
like image 55
Akrion Avatar answered Sep 26 '22 17:09

Akrion