0

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'

M Yil
  • 619
  • 8
  • 22

1 Answers1

1

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.*"}}}'
uminder
  • 14,658
  • 3
  • 20
  • 45
  • Thank you for your response, Will it work like this also ? "$regex": "^001" – M Yil Jan 22 '20 at 12:37
  • @Mi Yil: `"$regex": "^001"` should also work and is probably even better. – uminder Jan 22 '20 at 12:55
  • One more question, I'm trying to do it like this: "{\"selector\":{\"_id\":{\"$regex\":'^001'}}\"]}" – M Yil Jan 22 '20 at 14:07
  • Have I been doing someonething wrong in that code piece? – M Yil Jan 22 '20 at 14:08
  • @Mi Yil: Hard to say if your code is fine without knowing in what context it gets executed. I added an example to my answer that illustrates how this can be done with CURL. – uminder Jan 22 '20 at 14:46
  • Hi, thanks again for your response! My very last question, I want the fourth value to be an "_", an underscore. Can you please provide me with infomration, it's almost working! – M Yil Jan 22 '20 at 15:16
  • Found it: "$regex": "^000_" Thanks for all your help sir! – M Yil Jan 22 '20 at 15:22