Wednesday 26 February 2020

Dates in MongoDB

I know this has been written about a lot, but I can't figure it out.I have a collection called "bracetimes" with a document, like this:_id: ObjectID(5e56cf9ae65bf2b30a6ab525) user_id: ObjectID(5e56bb2b40ad526200401773) start: 2020-02-26T00:00:00.000+00:00 // 12am stop: 2020-02-26T12:00:00.000+00:00 // noon The start and stop attributes are Date objects, ISOdate specifically (I thought that was the problem, but I'm not sure anymore).I have a search query that should find the above document, but does not: const startOfDay = moment().startOf('day').toISOString() const endOfDay = moment().endOf('day').toISOString() const currentTime = moment().toISOString() // search query { $and: [ { user_id: ObjectID(myUser._id) }, { $or: [ { $and: [{ start: { $gt: startOfDay } }, { start: { $lt: endOfDay } }] }, { $and: [{ stop: { $gt: startOfDay } }, { stop: { $lt: endOfDay } }] } ] } ] } Basically, I am looking for records that 1) match the right user_id and 2) have a start OR stop point between the startOfDay and endOfDay.I had essentially the same query working when the database was was holding unix integers, instead of dates (the moment constants were using .unix() instead of .toISOString() ), but now that I am trying to use dates I can't get it working.Any advice is much appreciated.

Submitted February 26, 2020 at 08:30PM by Briyo2289

No comments:

Post a Comment