Home > Software engineering >  mongodb comparing date entry with current date
mongodb comparing date entry with current date

Time:08-30

I want to aggregate entries whose date is less than 1 week old from today.

{
    "collection": "my-lovely-collection",
    "aggregate": [
        {"$match": {"some_field": { "$regex": "awesome*"}}},
        {"$match": {"created": {"$lt":
            {"$dateToString":
                {"date":
                    {"$dateSubtract":
                        {"startDate": {"$currentDate": {"$type": "date"}},
                        "unit": "day",
                        "amount": 7
                    }}}}}}},
        {"$group": {"_id": "$some_field", "count": {"$sum": 1 }}},
        {"$sort":  [{"name": "count", "direction": 1}]}
    ]
}

When I use a hard-coded date for today everything works fine (but that's not what I want)

{"$match": {"created": {"$lt": "2022-08-29"}}}

CodePudding user response:

You could use $dateSubtract:

  {
    $match: {
      $expr: {
        $lt: [
          "$created",
          {
            $dateToString: {
              format: "%Y-%m-%d",
              date: {
                $dateSubtract: {
                  startDate: "$$NOW",
                  unit: "week",
                  amount: 1
                }
              }
            }
          }
        ]
      }
    }
  }

Mongo Playground: https://mongoplayground.net/p/QWT4ar4gbt0

Documentation: https://www.mongodb.com/docs/manual/reference/operator/aggregation/dateSubtract/

  • Related