CouchDB
01 / 02

HTTP API, Documents & Views

CouchDB: HTTP API, Documents & Views

CouchDB is a NoSQL document database storing JSON documents, accessed entirely over HTTP -- every operation is a standard request/response, no special client driver required. Its design centers on robust, conflict-tolerant multi-master replication, including offline-capable clients via PouchDB.

The HTTP API

# Every operation is plain HTTP -- curl works directly, no driver needed
curl -X PUT http://localhost:5984/mydb

# Create a document
curl -X PUT http://localhost:5984/mydb/doc1 \
  -H 'Content-Type: application/json' \
  -d '{"name": "Alice", "type": "article", "author": "Alice", "title": "Hello"}'

# Read it back -- includes the current _rev
curl http://localhost:5984/mydb/doc1
# { "_id": "doc1", "_rev": "1-abc123", "name": "Alice", ... }

# Update REQUIRES the current _rev -- optimistic concurrency control
curl -X PUT http://localhost:5984/mydb/doc1 \
  -d '{"_rev": "1-abc123", "name": "Alice Updated"}'

# Stale _rev -> 409 Conflict: the doc changed since you last fetched it,
# client should re-fetch and retry, not overwrite blindly

# Binary attachments -- no base64 encoding into the JSON body needed
curl -X PUT http://localhost:5984/mydb/doc1/photo.jpg?rev=2-def456 \
  -H 'Content-Type: image/jpeg' --data-binary @photo.jpg

Views: Map/Reduce Indexes

// Design document (_design/app) -- stores view definitions,
// replicates alongside regular data like any document
{
  "_id": "_design/app",
  "views": {
    "articles_by_author": {
      "map": "function(doc) { if (doc.type === 'article') emit(doc.author, doc.title); }"
    },
    "article_count_by_author": {
      "map": "function(doc) { if (doc.type === 'article') emit(doc.author, 1); }",
      "reduce": "_count"
    }
  }
}

// Query the view -- CouchDB incrementally maintains this index,
// only re-running map/reduce against documents that changed since
// the index was last brought up to date -- not a full rescan per query
// GET /mydb/_design/app/_view/articles_by_author?key="Alice"

Mango Queries (_find)

# Declarative, MongoDB-style query -- no explicit map/reduce needed
curl -X POST http://localhost:5984/mydb/_find \
  -H 'Content-Type: application/json' \
  -d '{
    "selector": { "type": "article", "views": { "$gt": 100 } },
    "sort": [{"views": "desc"}]
  }'

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free