如何从mongodb中过滤出(日期+年份(都来自数据库))和今天的日期之间的差值小于或等于一个月的数据

pn9klfpd  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(123)

存在一个模式,

const schemaDB = mongoose.Schema({
  product:{
    type: String,
  },
  DateOfInstallation: {
    type: Date
  },
  standardWarranty: {
    type: Number
  },
  extendedWarranty: {
    type: Number
  },
  AMC:{
    type: Number
  }
})

我需要得到所有产品的清单,将到期1个月内从今天开始。

total_years_to_Add = standardWarranty  + extendedWarranty + AMC
date_exp = DateOfInstallation + addYears(total_years_to_Add) 
date_diff = date_exp - today's Date

如果date_diff小于月份,则返回数据
请帮助调试给定的mongodb聚合查询(在mongoose中实现)

const datas = await DBModel.aggregate([
{
$match: {
total: { $add: ['$standardWarranty','$extendedWarranty','$AMC']},
newdate: { $dateAdd: {
startDate: '$DateOfInstallation',
unit: "year",
amount: "$$total"
}},
$lte: [{$dateDiff:{
startDate: "$$newdate",
endDate: new Date(),
unit: "month"
}},1]
}},
{ $project:{
"DateOfInstallation":1, "standardWarranty":1, "extendedWarranty":1,"AMC":1
}},
{$sort:{
"DateOfInstallation": 1
}}
])

我知道$add不能在$match中使用,有人可以帮助查询相同的内容吗

1qczuiv0

1qczuiv01#

您的方向是正确的。但是您必须使用$expr

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $lte: [
          {
            $dateDiff: {
              startDate: {
                $dateAdd: {
                  startDate: "$DateOfInstallation",
                  unit: "year",
                  amount: {
                    $add: [
                      "$standardWarranty",
                      "$extendedWarranty",
                      "$AMC"
                    ]
                  }
                }
              },
              endDate: new Date(),
              unit: "month"
            }
          }, 1
        ]
      }
    }
  },
  {
    $project: {
      "DateOfInstallation": 1,
      "standardWarranty": 1,
      "extendedWarranty": 1,
      "AMC": 1
    }
  },
  { $sort: { "DateOfInstallation": 1 } }
])

或者更容易理解一点:

db.collection.aggregate([
  {
    $set: {
      total: {
        $add: [
          "$standardWarranty",
          "$extendedWarranty",
          "$AMC"
        ]
      }
    }
  },
  {
    $set: {
      newdate: {
        $dateAdd: {
          startDate: "$DateOfInstallation",
          unit: "year",
          amount: "$total"
        }
      }
    }
  },
  {
    $set: {
      dateDiff: {
        $dateDiff: {
          startDate: "$newdate",
          endDate: new Date(),
          unit: "month"
        }
      }
    }
  },
  { $match: { "$dateDiff": { $lt: 1 } } },
  {
    $project: {
      "DateOfInstallation": 1,
      "standardWarranty": 1,
      "extendedWarranty": 1,
      "AMC": 1
    }
  },
  { $sort: { "DateOfInstallation": 1 } }
])

相关问题