Home > OS >  MongoDB $nin AND equal to certain value
MongoDB $nin AND equal to certain value

Time:10-19

Is it possible to consolidate the following

{
  $and : [
      {foo: {$nin: ARR_TO_EXCLUDE}},
      {foo: SOME_VAL}
]}

I want to query docs where foo unconditionally is not equal to a list of values and where it could be another value too.

Would this even make sense to consolidate?

Thanks!

CodePudding user response:

I think it should be replaced with a condition independ of the foo field, and it can be done before sending the query.

{
  $and : [
      {foo: {$nin: ARR_TO_EXCLUDE}},
      {foo: SOME_VAL}
]}

<=>

SOME_VAL not-in ARR_TO_EXCLUDE   //(no matter what foo value has)

so istead of writting that $and, replace it with something like the bellow in your driver programing language

ARR_TO_EXCLUDE.not-contains(SOME_VAL)

If SOME_VAL and ARR_TO_EXCLUDE are variables of the driver programming language.
If they are fields or mongodb variables then check this contition in mongodb but its independend of the foo field

  • Related