Gokulraj Rajan
Gokulraj Rajan

Reputation: 57

how to use $or operator in CouchDB?

I am trying to query on CouchDB like below

[{
    "selector": {
        "docType": "student_details",
        {
            $or: ["studentName": {
                "$regex": "John"
            }, "studentAge": {
                "$regex": "15"
            }]
        }
    }
}]

but it is not working. Indexes are created on "studentName" and "studentAge". I am trying to get an output if either of the expression has a result.

However the following query works,

[{
    "selector": {
        "docType": "student_details",
        "studentName": {
            "$regex": "John"
        }
    }
}]

This gives me an output for studentName with John

Upvotes: 1

Views: 700

Answers (1)

uminder
uminder

Reputation: 26150

It looks like your first JSON is not of valid format. Also CouchDB expects operators to be enclosed in double quotes but $or is missing them.

You don't need to use $regex if you look for equality, the $eq operator is better suited. The selector can be written as follows.

"selector": { 
   "docType": "student_details",
   "$or": [ 
      { 
         "studentName": { 
            "$eq": "John"
         }
      },
      { 
         "studentAge": { 
            "$eq": 15
         }
      }
   ]
}

Or even simpler with implicit operators (not an option if you really have to use $regex).

"selector": { 
   "docType": "student_details",
   "$or": [ 
       { "studentName": "John" },
       { "studentAge": 15 }
   ]
}

Please note that this solution presumes that studentAge is of type number.

Upvotes: 1

Related Questions