Search code examples
databasecouchdbcouchdb-mango

CouchDB - Mango Query to select records based on complex composite key


I have records with keys looking like this:

  1. "001_test_66"
  2. "001_testab_54"
  3. "002_testbc_88"
  4. "0020_tesgdtbc_38"

How can I query a couchdb database using Mango queries based on the first part of the key (001 or 002). The fourth one should fail if I search on '002'


Solution

  • You can use $regex operator described in chapter Condition Operators of CouchDB API Reference. In below example, I assumed _id to be the key you want to search by.

    "selector": {
        "_id":  {
            "$regex": "^001.*"
        }
    }
    

    Here's an example using CURL (replace <db> with the name of your database).

    curl -H 'Content-Type: application/json' -X POST http://localhost:5984/<db>/_find -d '{"selector":{"_id":{"$regex": "^001.*"}}}'