0

I have a mongoDB ( collection with documents possibly containing two dates, dateA and dateB. These dates aren't guaranteed to be set, and can be null.

I want to write a find query that expresses:

    if dateA is not null:
            if dateA is less than someArbitraryDate
    or
    if dateB is not null:
            if dateB is less than someArbitraryDate

Looking at this answer, I know I probably need to use $expr and $cond. I'm just not sure how to write the find.

2
  • are you saying you want the query alone? or do you need it in spring data? Commented Jun 30, 2020 at 17:48
  • I'm not using spring, just the Java driver. I think the query alone would suffice for me to figure out how to use it in Java. Commented Jun 30, 2020 at 17:53

1 Answer 1

1

You do not need $expr or $cond for the simple use case that you stated. We can achieve the same with just $or.

The query will be something like:

db.collection.find({
    "$or": [
        {"dateA": {"$exists": true, "$ne": null, "$lt":  ISODate("<YYYY-mm-ddTHH:MM:ss>")}},
        {"dateB": {"$exists": true, "$ne": null, "$lt":  ISODate("<YYYY-mm-ddTHH:MM:ss>")}},
    ]
})

Here $exists ensures the field is present, $ne: null ensures the value is not null and then just a less than match to a date string will give you what you want in one if-if block you wrote

Combining them with $or will just combine the results from each of the dateA and dateB matches.

Read more on the operators from: https://docs.mongodb.com/manual/reference/operator/query-comparison/

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

1 Comment

Good point. I think this should work for my scenario, thanks!

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.