DEV Community

Cover image for NodeJS, MongoDB - "OR" queries - series #05
Functional Javascript
Functional Javascript

Posted on • Updated on

NodeJS, MongoDB - "OR" queries - series #05

Intro

When querying the database in MongoDB, all "Matches" you perform are conjunctions (i.e. "AND" operations).

To perform disjunction queries (i.e. "OR" operations), I'll use a wrapper func (helper func) called "matchOr".

Here's an example. For an indepth explanation, see the Notes section below.

lpromise(
  mgArr(dbEnum.nlpdb, collEnum.users_actions,
    matchExact("type", "inquiry"),
    matchOr(existsNot("isDeleted"), isFalse("isDeleted")),
    lastInserted(5),
  )
);
Enter fullscreen mode Exit fullscreen mode

Notes

  • USECASE Let's say users of our website are submitting inquiries. We want to have a look at the last few inquiries.

  • We want to exclude deleted inquiries. Deleted docs (records) are soft-deletes, meaning they are flagged as deleted (isDeleted=true) rather than actually hard deleted from the db collection.

  • The disjunct (the "OR") situation is that if there is no isDeleted field then the doc has never been deleted. But if there is an isDeleted field, only in cases where it's value is true is it deleted.

  • The matchExact("type", "inquiry") stage filters by only correspondence types that are inquiries (this is an "AND" filter).

  • The matchOr stage reads as this, "return the record if there is no isDeleted field, OR, return the record if the isDeleted field exists but its value is false". With this we are filtering out any "isDeleted=true"

  • The last stage just retrieves the last 5 inserted records.

  • The raw Mongo Aggregation Framework Stage syntax would look like this...

{ $match: { $or: [{ isDeleted: { $exists: false } }, { isDeleted: false }] } },
Enter fullscreen mode Exit fullscreen mode

So we've saved ourselves a bunch of curlies. :)

What's Next

  • If you have any questions, let me know, and I'll try my best to answer them.

  • Other constructs in the example code here like "lpromise" and "mgArr" were explained earlier in this article series, so make sure you read those if you are new to the series.

  • Tomorrow I'll show an interesting but very common type of operation:
    We want to update a document by pushing a document onto one of its fields that is of type array.

Res

https://docs.mongodb.com/manual/reference/operator/query/or/

Top comments (0)