Amitabha Saha
Amitabha Saha

Reputation: 29

date $match in aggregate function in mongodb

I want to write a query with a $match(where) condition in mongo db. I do not have any option to match only a date here. The query is below

db.LockContentAccess.aggregate([
                            {$match : {AccessDate:{$eq : new Date()}}},
                            {"$project" : 
                                     { .... }
                            }
                              ]);

Here the problem is I have no option to match only the date part like sql queries (not the time).

Can any one help me, please?

Upvotes: 0

Views: 598

Answers (1)

Philipp
Philipp

Reputation: 69663

The classname Date is a bit misleading, because it represents not just a calendar day but also includes the time, accurate to the millisecond. So when you query them with $eq : new Date() you will only get the documents which have a date-field with this millisecond. When you want the documents of a whole day, there are three possible workarounds.

  1. When you only need dates with day-precision anyway, truncate the date in your documents to midnight by setting the time to 0:00:00.000. When you query for a date, create a new Date object which also has the time set to 0:00:00.000.
  2. Query a range of dates with $gte: [todays date with time 0:00:00.000] and $lte [todays date with time 23:59:59.999]. This is what I would recommend you to do, because it retains the exact time in case you need it for another use-case.
  3. Ditch the whole inbuilt Date handling stuff and store your dates as an integer representing days elapsed since a specific date in the past. I would not recommend this, but when you are sure you don't need any of the special features MongoDB offers for date handling, it is an option.

How to change the time of a new Date() object depends on what programming language you use.

Upvotes: 4

Related Questions