Jawadh Salih Rifath
Jawadh Salih Rifath

Reputation: 150

Mongo find query is not working for certain values.

I have written a Mongo search query which includes an OR operator. Its boolean expression is as follows.

A and (B or C) for the above layout of the expression, if one of B or C got false, it will return false. Hence my query fails. A more specific Mongo query is as follows.

{ "fieldName" : { "regex" : "AB.*" },
   "$and" : [[{"fieldName2" : "$in" : ["abc", "cds"]},
   "$or" : [{"fieldName3" : "$in" : ["abc", "cds"]}]]
}

In the above query, if fieldName2 has one of abc either cds but fieldName3 doesn't have any of that, then query returns false though it's in an OR clause.

So is there any other way I can implement this search query as in the mentioned expression or what I am doing wrong here. ?

Upvotes: 2

Views: 230

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311945

$and and $or apply their boolean operation over the contents of their array value. So your query should be rewritten as:

{
  "fieldName" : { "regex" : "AB.*" },
  "$or": [{"fieldName2" : "$in" : ["abc", "cds"]}, 
          {"fieldName3" : "$in" : ["abc", "cds"]}]
}

Note that you don't even need to use $and here because multiple query terms are implicitly AND-ed.

Upvotes: 2

Related Questions