【问题标题】:check date existence on array of string检查字符串数组上的日期是否存在
【发布时间】:2022-01-11 08:58:12
【问题描述】:

这是我来自 MongoDB 集合的数据集:


{
  "_id": "60c0ace96e93993880efd337",
  "lv": [
   uid: 1,
   "createdate": "2021-12-15T12:30:01.935Z",
   "updatedAt": [
      "2021-12-15T12:31:11.635Z",
      "2021-12-15T12:31:51.955Z",
      "2021-12-16T12:30:01.935Z",
      "2021-12-16T12:30:01.935Z",
      "2021-12-17T12:30:01.935Z",
      "2021-12-18T12:30:01.935Z"
   ]
  ]
},
{
...
}

我只想过滤掉日期范围在 createdate 列或 updatedAt 列中的数据。

我无法得到想要的结果。不知道我在哪里犯了查询或男女同校的错误。

我尝试过的我会在这里提及。

let startA = new Date("2021-12-14");
const a = new Date(startA.setHours(startA.getHours() - 5));
const start = new Date(a.setMinutes(startA.getMinutes() - 30));

let endA = new Date("2021-12-17");
const b = new Date(endA.setHours(endA.getHours() - 5));
const end = new Date(b.setMinutes(endA.getMinutes() - 30));

const fetchData = await MyCollection.findOne(
  { 
    _id: ObjectId(req.body.id),
    'lv.createdate': { $gte: start, $lt: end },
    'lv.updatedAt': {
      $elemMatch: { $gte: start, $lt: end }
    }
  }
).lean().exec();

非常感谢任何帮助或建议。提前感谢您的互动。

【问题讨论】:

  • “我只想过滤出日期范围位于 createdate 列或 updatedAt 列中的数据。” - 但是,您的查询过滤器正在使用隐式 and(不是)。
  • 您的示例数据不是有效的 JSON,请提供有效的示例。

标签: javascript node.js mongodb


【解决方案1】:

您的输入数据无效。有了一些假设,解决方案可能是这样的:

db.MyCollection.aggregate([
   {
      $set: {
         lv: {
            $map: {
               input: "$lv",
               as: "lv",
               in: {
                  $filter: {
                     input: "$$lv.updatedAt",
                     cond: {
                        $and: [
                           { $gte: ["$$this", start] },
                           { $lt: ["$$this", end] }
                        ]
                     }
                  }
               }
            }
         }
      }
   }
])

或者这个:

db.MyCollection.aggregate([
   {
      $set: {
         "lv.updatedAt": {
            $filter: {
               input: "$lv.updatedAt",
               cond: {
                  $and: [
                     { $gte: ["$$this", start] },
                     { $lt: ["$$this", end] }
                  ]
               }
            }
         }
      }
   }
])

【讨论】:

  • 感谢您的互动。我尝试了您共享的查询。但没有得到具体的价值。它将返回整个对象数组。不过滤掉值
猜你喜欢
  • 2020-06-23
  • 2012-06-17
  • 2021-12-27
  • 1970-01-01
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多