Search code examples
mongodbmongoosemongodb-querynosql-aggregation

Getting error while filtering record based on time


I have few record for a user in my collection. For that record insertion time is in toISOString format. I am trying to ignore the record which is more than 3 days old using find query but getting some error.

error: error in query: fail to parse content of query: invalid character '.' after array element

myRecord:

[
  {
    "_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",
  }
]

expected output:

[
  {
    "_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",
  }
]

Query i tried:

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

Can someone help me to resolve this?


Solution

  • Error is in this line new Date(Date.now() - 3 * 24 * 60 * 60 * 1000)

    You have to use $subtract to perform subtraction.

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

    Playground