根据时间过滤记录时出错

Getting error while filtering record based on time

我的 collection 中几乎没有用户记录。对于该记录,插入时间采用 toISOString 格式。我试图使用查找查询忽略超过 3 天的记录,但出现了一些错误。

错误:查询错误:无法解析查询内容:无效字符“.”在数组元素

之后

我的记录:

[
  {
    "_id": "1",
    "name": "user1",
    "data":"some data",
    "insertionTime": "2020-11-10T10:18:27.158Z",
  },
  {
    "_id": "2",
     "name": "user1",
    "data":"some data"
    "insertionTime": "2020-11-10T14:18:27.158Z",
  },
  {
    "_id": "3",
     "name": "user1",
    "data":"some data",
    "insertionTime": "2020-11-06T14:18:27.158Z",
  }
]

预期输出:

[
  {
    "_id": "2",
     "name": "user1",
    "data":"some data",
    "insertionTime": "2020-11-10T14:18:27.158Z",
  },
  {
    "_id": "3",
     "name": "user1",
    "data":"some data",
    "insertionTime": "2020-11-10T14:18:27.158Z",
  }
]

我试过的查询:

db.collection.find({ $expr: { $and: [ { $eq: ['$name', 'user1'] }, { $gte: [ { $dateFromString: { dateString: '$insertionTime' } }, new Date(Date.now() - 3 * 24 * 60 * 60 * 1000), ], }, ], }, });

有人可以帮我解决这个问题吗?

错误在这一行new Date(Date.now() - 3 * 24 * 60 * 60 * 1000)

您必须使用 $subtract 来执行减法。

db.collection.find({
  $expr: {
    $and: [
      {
        $eq: [
          "$name",
          "user1"
        ]
      },
      {
        $gte: [
          {
            $dateFromString: {
              dateString: "$insertionTime"
            }
          },
          {
            "$subtract": [
              new Date(Date.now()),
              259200000
            ]
          }
        ]
      }
    ]
  }
})

Playground