0

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"}}} 
2
  • Does this answer your question? MongoDB find Query comparision with CurrentDate Commented Aug 29, 2022 at 16:24
  • @DimiVi I can't seem to subtract 7 days from today and compare to that - even after using new Date() - any ideas? thanks ! Commented Aug 29, 2022 at 16:32

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

5 Comments

I can't seem to subtract 7 days from today and compare to that
Gotcha. Updated my answer
Arrrggghh ... still not working - You don't use the "$dateToString" - is it not needed? (you also have a typo with an extra $ in "$created"
@OrenIshShalom so I assume your created field is a string. If yes so I updated my answer in accordance, please take a peek. If no, please provide your collection schema for better visibility :)
thanks for the mongo playground link !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.