如何在MongoDB中使用聚合手动将日期增加7天?

huangapple go评论49阅读模式
英文:

how to add 7 days in date manually using mongodb(aggregation)?

问题

{
"$match": {
"publishedAt": {
"$lt": new Date(startDate),
"$gte": new Date(endDate)
}
},
"$set": {
"publishedAt": {
"$add": [new Date(startDate), 1000 * 60 * 60 * 24 * 7]
}
}
}

英文:

I have a query in which I'm getting data using start Date and end Date. And it's working perfectly fine. now I want to add 7 days in my start date using aggregation and want to get data of start Date + 7 added days. i have tried the below code but couldn't get any success


  {
    $match: {
      publishedAt: {
        $lt: new Date(startDate),
        $gte: new Date(endDate),
      },
    },
  },
  {
    $set: {
      publishedAt: {
        $add: [new Date(startDate), 1000 * 60 * 60 * 24],
      },
    },
  },

答案1

得分: 1

{
$set: {
publishedAt: {
$dateAdd: {
startDate: new Date(startDate),
unit: "day",
amount: 7
}
}
}
}

或者使用第三方库,例如Luxon

{
$set: {
publishedAt: DateTime.now().plus({ days: 7 }).toJSDate()
}
}

英文:

Use this:

   {
      $set: {
         publishedAt: {
            $dateAdd: {
               startDate: new Date(startDate),
               unit: "day",
               amount: 7
            }
         }
      }
   }

Or use a 3rd party library, e.g. Luxon

   {
      $set: {
         publishedAt: DateTime.now().plus({ days: 7 }).toJSDate()
      }
   }

huangapple
  • 本文由 发表于 2023年2月16日 18:32:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75470973.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定