skip to Main Content

If there are documents with endDate,I want to fetch documents in a collection whose endDate+3 days is less than today through mongo query

The below query will find records whose endDate is less then today

const myCollection= DB_CONNECTION.collection(TRANSACTION);

let expiredTrans = await myCollection.find({ "endDate": { $lt: curTime}}).toArray();

I need to add 3 days to that endDate and then fetch records.

2

Answers


  1. You need the $dateAdd operator, but since it is an aggregation operator, you need to work with the $expr operator.

    Optional, you can replace curTime with $$NOW which is a MongoDB variable to get the current time.

    db.collection.find({
      $expr: {
        $lt: [
          {
            $dateAdd: {
              startDate: "$endDate",
              unit: "day",
              amount: 3
            }
          },
          "$$NOW"// curTime
          
        ]
      }
    })
    

    Demo @ Mongo Playground

    Login or Signup to reply.
  2. You can try this

    let expiredTrans = await myCollection.find({
      $expr: {
        $lt: [
          { $add: ["$endDate", 3 * 24 * 60 * 60 * 1000] }, // Add 3 days in milliseconds
          "$$NOW"// curTime
        ]
      }
    }).toArray();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search