skip to Main Content

I am trying to query information by entering either value 1 or value 2 from the database. Here is the body of the request:

{
  "query": {
    "Value1": {"$regex": "222"}
      "value2": {"regex":"359"}
    
  }

}

I tried:

{
  "query": {
"$or": [
    "Value1": {"$regex": "222"},
      "value2": {"regex":"359"}
]
    
  }

}

expecting a response of either value1 or value2

2

Answers


  1. You can check the details of "or operator" from the mongodb docs:

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

    { $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }
    
    db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } )
    
    Login or Signup to reply.
  2. As per documentation, MongoDB $or operator accepts array of conditions, while you pass conditions as one object.

    The correct syntax would be like this:

    db.collection.find({
      "$or": [
        {
          "Value1": {
            "$regex": "222"
          }
        },
        {
          "value2": {
            "$regex": "359"
          }
        }
      ]
    })
    

    Here is a link to playground to see query work.

    Also, you seem to have tried passing array already, but you made a mistake in second condition. You had regex while the proper operator name is $regex, like in your first condition.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search