首页 > 解决方案 > MongoDB find() - 试图构造一个复杂的日期查询

问题描述

我正在尝试编写一个相当繁琐的 MongoDB 查询,它返回一组仅针对未来事件过滤的结果(事件)。

不幸的是,这些事件的数据模式有点令人沮丧。用户可以设置具有特定结束日期的事件(可以使用),或者他们可以选择在特定日期结束的重复(也可以)。

但是,他们也可以选择事件每 X 天/周/月重复一次的选项(有一个类型字段可以选择其中的哪一个),总共 Y 次重复。因此,如果我想计算一个有效的结束日期,我需要在我的查询中使用所有这三个变量。

我正在努力处理在 MongoDB 查询中操作日期的语法,使用数据库中的数据来构造一个新的日期对象......

这是我到目前为止构建的条件,正在尝试完成具有 /* */ 注释的 3 行。

如果有人知道这样做的方法,我将非常感谢任何帮助。谢谢!

$or: [
    { 'when.endingDate': { $gte: new Date() } },
    { 'when.recurring.forever': { $eq: true } },
    { 'when.multipleDays': { $eq: true } },
    {
      $and: [
        { 'when.recurring.occurences': { $gte: 1 } },
        { $or: [
          { $and: [
            { 'when.recurring.type': { $eq: 'day' } },
            { /* when.endingDate + when.recurring.occurences * when.recurring.every * days >= new Date() */ }
          ] },
          {
            $and: [
              { 'when.recurring.type': { $eq: 'week' } },
              { /* when.endingDate + when.recurring.occurences * when.recurring.every * week >= new Date() */ }
            ]
          },
          {
            $and: [
              { 'when.recurring.type': { $eq: 'month' } },
              { /* when.endingDate + when.recurring.occurences X when.recurring.every * month >= new Date() */ }
            ]
          }
        ] }
      ]
    },
    { $and: [
      { 'when.repeat': { $eq: true } },
      { 'when.recurring.until': { $gte: new Date() } }
    ] }
  ]

标签: mongodbdatemongodb-query

解决方案


您正试图将大量业务逻辑塞进您的 mongodb 查询中。

我会选择以下方法之一:

  • 将 DB 流式传输到应用程序并以实际编程语言运行上述逻辑(首选);
  • 为上述查询准备数据。制作辅助字段并通过计划作业定期更新它们。

推荐阅读