0

I try to dynamically create a mongo query with dates.

This is a part of a JSON query I produced:

{"$or":[{"createdAt":{"$gte":"2017-08-31T22:00:00.000Z"}},{"modifiedAt":{"$gte":"2017-08-31T22:00:00.000Z"}}]}

but it does not work.

This is a part of code which stands behind it:

let result = {$or: [{createdAt: {$lte: new Date(date)}}, {modifiedAt: {$lte: new Date(date)}}]};

Spent 3 hours trying to find a solution. My understanding is that $lte here tries to compare mongo date object with a string describing date in ISO format. And it does not work well.

I do not know how to create a proper JSON object being a mongo query containing dates.

Please help! :-)

1 Answer 1

1

If you want to query Mongo with date range, you have to use a standard Date format (ISO-8601). To achieve this, try with moment:

        let date ="2019-02-22"; //for example, in my apis, you can set multiple type of date (YYYY-MM-DD, YYYYMMDD, DD-MM-YYYY,..) but date format with / is forbidden.
        let query = {$or:[{createdAt: {$lte: moment(date).format()}}, {modifiedAt:{$gte: moment(date).format()}}] //pass parameter to format, in this case it will use the default locale format

Like this you are setting a query. IMO querying on date range with "OR" condition is not useful: usually a date query in is "AND" condition (if you are querying on a single date, your query will be: greater than today or lower than today -> everything)

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

1 Comment

The code you proposed creates what I already have and it does not work: db.getCollection('videos').find({"$or":[{"createdAt":{"$gte":"2017-09-01T00:00:00+02:00"}},{"modifiedAt":{"$gte":"2017-09-01T00:00:00+02:00"}}]})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.