Search code examples
databasecouchdbcloudant

Document field must regex match one item in array


I have a cloudantDB instance which uses CouchDB query syntax. At a high level, inside my database I have documents which contain id values as such

{
  "id": "123-01"
},
{
  "id": "123-02"
},
{
  "id": "456-01"
},
{
  "id": "789-01"
}

What I am attempting to achieve is to query for all of the documents who's id field starts with 123 and 456, but not 789. Currently, I have achieved this by creating a large selector which uses the $or operator to match any $regex condition like:

{
  selector: {
    "$or": [{
      "id": {
        "$regex": "123"
      }
    },
      "id": {
        "$regex": "456"
      }
    ]

  }
}

Something tells me that this is not a proper way to achieve this result. Might anyone know of a more efficient way to query the database for documents like this?


Solution

  • If you only need to get documents with ID starting of a specific prefix, consider using _all_docs with a startkey. That should be a more elegant and more performant solution (instead of using regexes).