• Stars
    star
    433
  • Rank 97,953 (Top 2 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created over 9 years ago
  • Updated about 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Easy-to-use query language for PouchDB. ⚠️ NOTICE ⚠️: moved to the PouchDB repo

⚠️ NOTE ⚠️: this project has moved to the PouchDB GitHub repo. Please submit new issues/PRs there!

The pouchdb-find plugin is being incorporated into PouchDB itself. Original documentation follows:

PouchDB Find Build Status Coverage Status

(Live demo)

Provides a simple, MongoDB-inspired query language that accomplishes the same thing as the map/reduce API, but with far less code.

Eventually this will replace PouchDB's map/reduce API entirely. You'll still be able to use map/reduce, but it will be distributed as a separate plugin.

Status

Implemented: $lt, $gt, $lte, $gte, $eq, $exists, $type, $in, $nin, $all, $size, $or, $nor, $not, $mod, $regex, $elemMatch, multi-field queries, multi-field indexes, multi-field sort, 'deep.fields.like.this', ascending and descending sort.

0.2.0: $and, $ne

0.3.0: limit, skip, ddoc when creating an index

0.4.0: total_rows

0.5.0: $in, $nin, $all, $size

0.6.0: $or, $nor, $not

0.7.0: $elemMatch, $regex

0.8.0: Bug fixes for $and, $type, $exists

0.9.0: Bug fixes for $elemMatch. Rewrite of in-memory operator

0.10.0: Update for latest Mango spec (warnings instead of errors), update for PouchDB 5.4.0.

Usage

In the browser

To use this plugin in the browser, include it after pouchdb.js in your HTML page:

<script src="pouchdb.js"></script>
<script src="pouchdb.find.js"></script>

You can also download it from Bower:

bower install pouchdb-find

In Node.js/Browserify

Or to use it in Node.js, just npm install it:

npm install pouchdb-find

And then attach it to the PouchDB object:

var PouchDB = require('pouchdb');
PouchDB.plugin(require('pouchdb-find'));

API

This API is modeled after the Cloudant query API, merged into CouchDB 2.0. Read that page for more details.

As with PouchDB, the entire API accepts either the callback or the Promise style.

Overview

db.createIndex(index [, callback])

Create an index if it doesn't exist, or do nothing if it already exists.

Example:

db.createIndex({
  index: {
    fields: ['foo']
  }
}).then(function (result) {
  // yo, a result
}).catch(function (err) {
  // ouch, an error
});

The result can be either:

{"result": "created"} // index was created

or:

{"result": "exists"} // index already exists

You can also create an index on multiple fields:

db.createIndex({
  index: {
    fields: ['foo', 'bar', 'baz']
  }
});

Or an index on deep fields:

db.createIndex({
  index: {
    fields: ['person.address.zipcode']
  }
});

You can also specify additional options, if you want more control over how your index is created:

db.createIndex({
  index: {
    fields: ['foo', 'bar'],
    name: 'myindex',
    ddoc: 'mydesigndoc'
    type: 'json',
  }
});

Options

  • fields is a list of fields to index
  • name (optional) name of the index, auto-generated if you don't include it
  • ddoc (optional) design document name (i.e. the part after '_design/', auto-generated if you don't include it
  • type (optional) only supports 'json', and it's also the default

db.getIndexes([callback])

Get a list of all the indexes you've created. Also tells you about the special _all_docs index, i.e. the default index on the _id field.

Example:

db.getIndexes().then(function (result) {
  // yo, a result
}).catch(function (err) {
  // ouch, an error
});

Example result:

{
  "indexes": [
    {
      "ddoc": null,
      "name": "_all_docs",
      "type": "special",
      "def": {
        "fields": [
          {
            "_id": "asc"
          }
        ]
      }
    },
    {
      "ddoc": "_design/idx-0f3a6f73110868266fa5c688caf8acd3",
      "name": "idx-0f3a6f73110868266fa5c688caf8acd3",
      "type": "json",
      "def": {
        "fields": [
          {
            "foo": "asc"
          },
          {
            "bar": "asc"
          }
        ]
      }
    }
  ]
}

db.deleteIndex(index [, callback])

Delete an index and clean up any leftover data on the disk.

Options

  • index Definition of an index to delete. You can pass it in exactly as you received it from the getIndexes() API. You cannot delete the built-in _all_docs index.

Example:

db.deleteIndex({
  "ddoc": "_design/idx-0f3a6f73110868266fa5c688caf8acd3",
  "name": "idx-0f3a6f73110868266fa5c688caf8acd3",
  "type": "json",
  "def": {
    "fields": [
      {
        "foo": "asc"
      },
      {
        "bar": "asc"
      }
    ]
  }
}).then(function (result) {
  // yo, a result
}).catch(function (err) {
  // ouch, an error
});

Notice that you don't need to provide a _rev! The design doc is also deleted.

db.find(request [, callback])

Query the API to find some documents.

Example:

db.find({
  selector: {name: 'Mario'},
  fields: ['_id', 'name'],
  sort: ['name']
}).then(function (result) {
  // yo, a result
}).catch(function (err) {
  // ouch, an error
});

Example result:

{
  "docs": [
    {
      "_id": "mario",
      "name": "Mario"
    }
  ]
}

Options;

  • selector Defines a selector to filter the results. Required.

    • $lt Match fields "less than" this one.
    • $gt Match fields "greater than" this one.
    • $lte Match fields "less than or equal to" this one.
    • $gte Match fields "greater than or equal to" this one.
    • $eq Match fields equal to this one.
    • $ne Match fields not equal to this one.
    • $exists True if the field should exist, false otherwise.
    • $type One of: "null", "boolean", "number", "string", "array", or "object".
    • $in Matches if all the selectors in the array match.
    • $and Matches if all the selectors in the array match.
    • $nin The document field must not exist in the list provided.
    • $all Matches an array value if it contains all the elements of the argument array.
    • $size Special condition to match the length of an array field in a document.
    • $or Matches if any of the selectors in the array match. All selectors must use the same index.
    • $nor Matches if none of the selectors in the array match.
    • $not Matches if the given selector does not match.
    • $mod Matches documents where (field % Divisor == Remainder) is true, and only when the document field is an integer.
    • $regex A regular expression pattern to match against the document field.
    • $elemMatch Matches all documents that contain an array field with at least one element that matches all the specified query criteria.
  • fields (Optional) Defines a list of fields that you want to receive. If omitted, you get the full documents.

  • sort (Optional) Defines a list of fields defining how you want to sort. Note that sorted fields also have to be selected in the selector.

  • limit (Optional) Maximum number of documents to return.

  • skip (Optional) Number of docs to skip before returning.

If there's no index that matches your selector/sort, then this method will issue a warning.

The best index will be chosen automatically. If you want to see the query plan for your query, then turn on debugging.

See the Cloudant docs for more details.

Examples

Equals

Find all docs where doc.name === 'Mario':

db.find({
  selector: {name: {$eq: 'Mario'}}
});

This is equivalent to:

db.find({
  selector: {name: 'Mario'}
});

Multi-selectors

Find all docs where doc.series === 'Mario' and doc.debut > 1990:

db.find({
  selector: {
    series: 'Mario',
    debut: { $gt: 1990 }
  }
});

This is equivalent to:

db.find({
  selector: {
    $and: [
      { series: 'Mario' },
      { debut: { $gt: 1990 } }
    ]
  }
});

Sorting

Return all docs sorted by doc.debut descending:

db.find({
  selector: {
    debut: {'$exists': true}
  },
  sort: [{debut: 'desc'}]
});

For more examples, refer to Cloudant's _find documentation.

With a remote database

Over HTTP, this plugin currently works with Cloudant and CouchDB 2.0. Cloudant is the reference implementation, so the API should be the same.

PouchDB Server also has this API, since it includes this very plugin by default.

Debugging

Just call:

PouchDB.debug.enable('pouchdb:find')

Then pouchdb-find will start logging some debug information to the console. This can be useful if, for instance, you want to see the query plan that is being used to execute your queries.

Kudos

Thanks very much to @garrensmith for implementing all the new features from 0.4.0 to 0.6.0!

How to contribute to this thing

Instructions are in CONTRIBUTING.md.

More Repositories

1

optimize-js

Optimize a JS file for faster parsing (UNMAINTAINED)
JavaScript
3,754
star
2

fuite

A tool for finding memory leaks in web apps
JavaScript
3,488
star
3

pokedex.org

Offline-capable Pokédex web site (unmaintained)
JavaScript
2,269
star
4

marky

High-resolution JavaScript timer based on performance.mark/measure (491 bytes min+gz)
JavaScript
1,097
star
5

pinafore

Alternative web client for Mastodon (UNMAINTAINED)
JavaScript
1,021
star
6

emoji-picker-element

A lightweight emoji picker for the modern web
JavaScript
956
star
7

slow-deps

🐌 Measure which dependencies in a project are slowest to npm install (UNMAINTAINED)
JavaScript
513
star
8

blob-util

Cross-browser utils for working with binary Blobs
TypeScript
489
star
9

Catlog

Logcat-reading app for Android (UNMAINTAINED)
Java
471
star
10

promise-worker

Promise-based messaging for Web Workers and Service Workers
JavaScript
465
star
11

rollupify

Browserify transform to apply Rollup (UNMAINTAINED)
JavaScript
386
star
12

cjs-to-es6

CLI to convert CommonJS to ES6 modules (UNMAINTAINED)
JavaScript
262
star
13

pseudo-worker

A tiny and mostly spec-compliant WebWorker polyfill
JavaScript
243
star
14

cordova-plugin-sqlite-2

Native SQLite database API for Cordova/PhoneGap/Ionic, modeled after WebSQL (UNMAINTAINED)
JavaScript
169
star
15

CustomFastScrollViewDemo

Demo of an Android app using a FastScrollView with non-alphabetic overlays.
Java
130
star
16

pouchdb-electron

PouchDB for Electron (formerly Atom Shell)
126
star
17

hello-javascript

Demo of a JavaScript module that supports many publishing options
JavaScript
121
star
18

jison-debugger

UI for debugging Jison grammars (UNMAINTAINED)
JavaScript
117
star
19

pretty-s3-index-html

A prettier index.html for listing public files and folders in Amazon S3 buckets. (UNMAINTAINED)
HTML
112
star
20

node-websql

The WebSQL Database API, implemented for Node.js
JavaScript
87
star
21

SuperSaiyanScrollView

Super-fast, super-lightweight sectioned lists for Android
Java
81
star
22

state-of-binary-data-in-the-browser

The state of binary data in the browser (2015)
79
star
23

KeepScore

Score keeping app for Android (unmaintained)
Java
68
star
24

rollup-comparison

compare rollup to browserify/webpack
JavaScript
67
star
25

vdom-as-json

Convert virtual-dom objects to and from JSON (UNMAINTAINED)
JavaScript
64
star
26

database-comparison

Compare DOM-blocking in browser databases
JavaScript
58
star
27

vdom-serialized-patch

Serialize virtual-dom patches as a minimal JSON object (UNMAINTAINED)
JavaScript
56
star
28

pouchdb-phonegap-cordova

PouchDB for PhoneGap/Cordova
55
star
29

chord-magic

Musical chord parser, transposer, and disambiguator in JavaScript
JavaScript
54
star
30

html5workertest

Show which APIs are supported in Web Workers and Service Workers (UNMAINTAINED)
JavaScript
53
star
31

resources-for-mastodon-newbies

Links and tips for Mastodon newbies
53
star
32

fruitdown

Browser-based LevelDOWN adapter that works over Apple IndexedDB (UNMAINTAINED)
JavaScript
50
star
33

vuvuzela

Simple and non-recursive JSON parse/stringify library
JavaScript
45
star
34

AppTracker

Android app that logs app usage statistics in a background Service and displays app information (most frequently used, most recently used, etc.) in a widget or in the main activity.
Java
42
star
35

cost-of-small-modules

Benchmark showing the cost of various bundlers (repo locked 🔒)
Shell
38
star
36

pouchdb-async-storage

PouchDB adapter for AsyncStorageDOWN for use in React Native (INCOMPLETE)
JavaScript
37
star
37

ChordReaderRoot

Android app for reading and transposing downloaded guitar chord charts. (unmaintained)
Java
29
star
38

PouchDroid

PouchDB + Android = deliciously synchronous (DEPRECATED! DO NOT USE!)
JavaScript
29
star
39

async-functions-in-pouchdb

Demo of ES7 async functions in PouchDB
JavaScript
28
star
40

pouchdb-ionic

PouchDB for Ionic Framework
27
star
41

arrow-key-navigation

Add left/right focus navigation to a web app or KaiOS app
JavaScript
23
star
42

base64-encode-string

Simple module that converts a string to base64 (for educational purposes)
JavaScript
23
star
43

pouchdb-with-service-workers

Repo for brainstorming on PouchDB replication with service workers
22
star
44

tiny-queue

Simple JavaScript FIFO queue implementation to avoid having to do shift()
JavaScript
21
star
45

css-talk-2022

Talk given in October 2022 for perf.now about CSS runtime performance
JavaScript
21
star
46

pouchdb-nw

PouchDB for NW.js (aka Node-Webkit)
20
star
47

OfflineBrowser

Android app to view HTML pages offline.
Java
19
star
48

test-optimize-js

Web page to test optimize-js against any JavaScript file
JavaScript
19
star
49

serviceworker-update-demo

Effort to write a ServiceWorker demo app that properly manages updates
JavaScript
16
star
50

JapaneseNameConverterRoot

Android app to convert English names into Japanese characters.
Java
16
star
51

SimpleTalker

Simple Android app to speak some text passed in as a parameter. Intended to be used from the command line.
Java
16
star
52

pouchdb-ionic-hello-world

PouchDB Ionic "hello world" app (using Ionic v1)
JavaScript
15
star
53

pouchdb-cordova-hello-world-with-sqlite-plugin

"Hello world" Cordova app with PouchDB, using the SQLite Plugin
CSS
15
star
54

mingz

Check the browserified+min+gz size of any npm module (bash script)
14
star
55

braziljs-2016

Nolan's BrazilJS talk: "We can work it out: from Web Workers to Service Workers"
JavaScript
14
star
56

PopupDemo

Demo of a Quick Action-like popup in Android
Java
14
star
57

open-stylable

Web component where styles leak in, but they don't leak out
JavaScript
13
star
58

substring-trie

Minimalistic trie implementation for prefix searches
JavaScript
13
star
59

cordova-prepopulated-database-demo

Demo of prepopulated databases in Cordova SQLite Plugin 2
JavaScript
12
star
60

pouchdb-nw-hello-world

Demo of using PouchDB in NW.js (aka Node-WebKit)
JavaScript
12
star
61

package-json-versionify

Browserify transform to strip everything from package.json except for the "version" field.
JavaScript
12
star
62

measure-style-and-layout

Demo of measuring style and layout in a webapp
HTML
10
star
63

pouchdb-ionic-2-typescript-demo

Demo of PouchDB with Ionic 2 and TypeScript
JavaScript
10
star
64

browserify-count-modules

Count the total number of modules in a Browserify bundle.
JavaScript
10
star
65

web-starter-kit-rollupify

web starter kit, but with browserify+watchify+rollupify
HTML
10
star
66

webworker-postmessage-perf-test

Web Worker postMessage() benchmark
HTML
9
star
67

pouchdb-chrome-app

PouchDB for Chrome packaged apps
9
star
68

lodash-bundle-size-test

Test repo for experimenting with babel-plugin-lodash and lodash-webpack-plugin
JavaScript
8
star
69

emoji-mart-outside-react

Demo of how to use emoji-mart outside of React
JavaScript
8
star
70

throw-max-listeners-error

Throw an error if the max number of EventEmitter listeners is exceeded
JavaScript
7
star
71

pouchdb-getting-started-todo

Complete PouchDB "Getting Started" Todo app
CSS
7
star
72

memory-leaks-2020

Slides for a talk given at QueensJS in August 2020
HTML
7
star
73

database-comparison-worker-pouch

Fork of https://github.com/nolanlawson/database-comparison to demo worker-pouch
JavaScript
7
star
74

pouchdb-adapter-cordova-sqlite-demo

Demo of using pouchdb-adapter-cordova-sqlite in an Ionic 1 project (note: PouchDB v6, Ionic v1)
JavaScript
7
star
75

sugar-pouch

A sweeter, simpler interface for PouchDB (work in progress)
6
star
76

pouchdb-chrome-app-hello-world

"Hello world" Chrome app with PouchDB
JavaScript
6
star
77

shadow-selector-benchmark

Benchmark of shadow DOM with various CSS selectors
JavaScript
6
star
78

debug-websql

Simple script to console.log every SQL query received by Web SQL
JavaScript
6
star
79

sqlite-plugin-fork

Fork of the SQLite plugin from 2014, back when it was compatible with PouchDB
JavaScript
6
star
80

pouchdb-cordova-hello-world

"Hello world" Cordova app with PouchDB
CSS
6
star
81

fabric-calculator

Web app to calculate how much fabric you need for a sewing project
Svelte
6
star
82

RelatednessCalculator

Java library for parsing English relative names ("mom," "dad," "grandma," etc.) and calculating relatedness coefficients.
Java
6
star
83

pouchdb-perf-report-3.10

PouchDB Performance Report for v3.1.0, November 2014
5
star
84

pouchdb-prebuilt-demo

Demo of a prebult PouchDB database, used in a Cordova app.
JavaScript
5
star
85

async-functions-with-regenerator

A "hello world" for async/await with Babel and Regenerator
JavaScript
5
star
86

CatLogDonate

Java
5
star
87

webperf-2016-03

Nolan's 30-minute talk on Web Workers for the NYC Web Performance meetup in March 2016.
JavaScript
5
star
88

ultimate-crossword-app

The Ultimate Crossword - an online crossword puzzle (UNMAINTAINED)
JavaScript
5
star
89

react-wheel-jank-demo

Demo of a React app that causes janky scrolling by attaching a wheel event to the entire document
JavaScript
5
star
90

couch-community-compat-table

The state of sync pairs in the Couch community
4
star
91

offlinefirst-2016-03

Nolan's presentation for Offline First meetup, Boston March 2016
JavaScript
4
star
92

pouchdb-ionic-2-hello-world-with-sqlite

PouchDB "Hello world" app using Ionic v2, with native SQLite
TypeScript
4
star
93

async-rect

DEPRECATED - do not use
JavaScript
4
star
94

RelatednessCalculatorInterface

Grails frontend interface for the RelatednessCalculator
JavaScript
4
star
95

jnameconverter-server

JapaneseNameConverter simple RESTful web server
Java
4
star
96

cascadia-2016

Nolan's talk on Web Workers and Service Workers for Cascadia Fest 2016
JavaScript
4
star
97

starwars-data

generate data for the starwars-offline app
Python
4
star
98

pwa-deploy

Deploy a Progressive Web App to a connected Android device or emulator (EXPERIMENTAL - DON'T USE THIS)
Java
4
star
99

async-functions-with-kneden

A "hello world" for async/await with Babel and Kneden
JavaScript
3
star
100

independent-rendering-test

Independent Rendering test demo
JavaScript
3
star