Search all objects created in a specific day

In the database i have a createdAt : 2016-09-15T06:13:00.000Z

How can i do something like this?

total = Items.find({ createdAd: '2016-09-15' }).count()

You’re storing this as a string, rather than a Date object?

You could use a regular expression: Items.find({ createdAd: { $regex: '^2016-09-15' } }), or a range test: Items.find({ createdAd: { $gte: '2016-09-15T00:00:00Z', $lte: '2016-09-15T23:59:59Z' } ).

I also recommend ensuring you have an index on this field.

Ummm actually searching with meteor mongo it’s

"createdAt" : ISODate("2016-09-15T13:21:00Z")

, so that means it’s a Date, and probably that’s why your example doesn’t work.

Previously i got the data by copy/paste from MeteorChef field.

You will need to do a range check (like the string one above, but using Date objects). The start of day is easy: new Date('2016-09-15'), the end of day is best determined by making the test “less than the start of the next day”, which ensures that you capture any odd ms right at the end of the day. What you essentially want is:

Items.find({ createdAt: { $gte: new Date('2016-09-15'), $lt: new Date('2016-09-16') } )

However, to avoid doing the date calculation yourself, it’s probably easiest to use moment (you’ll need to install it if you haven’t already).

const startDate = new Date('2016-09-15');
const endDate = moment(startDate).add(1, 'days').toDate();
Items.find({ createdAt: { $gte: startDate, $lt: endDate) } )

Again, make sure you’ve indexed your createdAt field or this can hit your collection pretty hard.

1 Like

Depending on performance issues you might also might want to consider adding createdDay so you don’t need to use $lt and $gt which are slower to search with.