Home > database >  Combining regular MongoDB query operators with the $or operator
Combining regular MongoDB query operators with the $or operator

Time:11-28

I am trying to combine a regular MongoDB query operator with an $or operator, but I am getting an unexpected result.

Say I have these records:

[
  {
    "foo": "foo",
    "bar": "bar",
    "baz": null
  },
  {
    "foo": "foo",
    "bar": "rab",
    "baz": "zab"
  }
]

As you see, they share the foo value, but diverge in the bar and baz values.

If I run this query:

{
  "foo": "foo",
  "$or": [
    {
      "bar": "bar",
      "baz": "baz"
    }
  ]
}

I get no results. Any ideas why? I expected it to match my first document.

But if I run this query that only includes a single expression inside of the $or block:

{
  "foo": "foo",
  "$or": [
    {
      "bar": "bar"
    }
  ]
}

I do get a match on the first document. From the docs it is stated that an $or operator needs two or more expressions. Which means maybe it's just evaluating an $or query with a single expression as a normal expression.

CodePudding user response:

The problem you're having is because of how you're using the expression in your $or, you're giving him a single expression object and expect him to do or logic on that expression, that's not how it works.

What you want to do is just give him multiple expressions, like so:

{
    "foo": "foo",
    "$or": [
        {
            "bar": "bar",
        },
        {
            "baz": "baz"
        }
    ]
}
  • Related