mongodb聚合以在2个日期之间获取数据

时间:2018-10-21 02:40:53

标签: mongodb express

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'
            }
    })]

我上面有一个查询,该查询使用express从mongodb获取数据。我想选择两个日期之间。但是,当我添加以下代码行时,上面的代码不起作用:

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

我究竟可以添加这些语句以获取2个日期的数据吗?

1 个答案:

答案 0 :(得分:2)

MongoDB的默认日期为ISODate。不要在日期上执行replace

相反,只需将它们作为新日期传递即可:

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'
    }
  })]