PouchDB get documents by ID with certain string in them
Asked Answered
D

3

7

I would like to get all documents that contain a certain string in them, I can't seem to find a solution for it..

for example I have the following doc ids

vw_10
vw_11
bmw_12
vw_13
bmw_14
volvo_15
vw_16

how can I get allDocs with the string vw_ "in" it?

Dumbstruck answered 25/1, 2015 at 15:37 Comment(0)
B
11

Use batch fetch API:

db.allDocs({startkey: "vm_", endkey: "vm_\ufff0"})

Note: \ufff0 is the highest Unicode character which is used as sentinel to specify ranges for ordered strings.

Bainter answered 25/1, 2015 at 16:22 Comment(3)
thanks for the reply it worked. Can I ask where you got the uff0 part?Dumbstruck
@Dumbstruck docs.couchdb.org/en/latest/couchapp/views/…Bainter
Note: startkey and endkey only find keys that begin with the given sequence. The above function call would not find 'uvw_10'...Notions
N
5

You can use PouchDB find plugin API which is way more sophisticated than allDocs IMO for querying. With the PouchDB find plugin, there is a regex search operator which will allow you do exactly this.

db.find({selector: {name: {$regext: '/vw_'}}});

It's in BETA at the time of writing but we are about to ship a production app with it. That's how stable it has been so far. See https://github.com/nolanlawson/pouchdb-find for more on Pouch Db Find

Narcisanarcissism answered 11/1, 2017 at 12:54 Comment(3)
I had to use $regex because I got this: Error: unknown operator "$regext" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all.Revivalism
@Revivalism he misspelled regex as regext (or maybe the selector name was changed in the past).Solis
This answers the question, but if someone is interested in a case-insensitive search, replace '/vw_' with RegExp(<string>, "i"). Credit goes to this answer.Frap
F
0

You better have a view with the key you want to search. This ensures that the key is indexed. Otherwise, the search might be too slow.

Forwarder answered 28/1, 2015 at 0:49 Comment(1)
You mean something like this vw/10, vw/11, vw/13?Dumbstruck

© 2022 - 2024 — McMap. All rights reserved.