Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

So I have an embedded document that tracks group memberships. Each embedded document has an ID pointing to the group in another collection, a start date, and an optional expire date.

I want to query for current members of a group. "Current" means the start time is less than the current time, and the expire time is greater than the current time OR null.

This conditional query is totally blocking me up. I could do it by running two queries and merging the results, but that seems ugly and requires loading in all results at once. Or I could default the expire time to some arbitrary date in the far future, but that seems even uglier and potentially brittle. In SQL I'd just express it with "(expires >= Now()) OR (expires IS NULL)" -- but I don't know how to do that in Mongo.

Any ideas? Thanks very much in advance.

2 Answers

0 votes
by (106k points)

Your query of "(expires >= Now()) OR (expires IS NULL)" can now be rendered as:

{$or: [{expires: {$gte: new Date()}}, {expires: null}]}

0 votes
by (107k points)

Query Mongo does the translation between SQL and MongoDB, including OR clauses. It can be really effective for figuring out syntax when you know the SQL equivalent.

In the case of OR statements, it looks like this

SQL:

SELECT * FROM collection WHERE columnA = 3 OR columnB = 'string';

MongoDB:

db.collection.find({ "$or": [{ "columnA": 3 }, { "columnB": "string" }] });

Related questions

0 votes
2 answers
asked Oct 16, 2019 in Web Technology by Sammy (47.6k points)
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...