Mango Selectors, Views and Document Modeling

Article · 7:00

Mango queries and their indexes, design documents, map/reduce views with grouping, and the modelling that one flat database forces.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

Everything lives in one flat namespace per database. There are no collections or tables - a database holds documents, full stop. The universal convention is a type field on every document, and your queries and views filter on it. This feels wrong coming from anywhere else and it is genuinely how CouchDB is used.

That shapes modelling in a specific way. Because there are no joins, related data is either embedded in one document or fetched in a second request. And because replication operates per document, the document is also the unit of conflict - two devices editing different fields of the same document still conflict. The consequence is a genuine design pressure in CouchDB that does not exist in MongoDB: split documents along the lines of who edits them. A survey response whose answers one person fills in and whose review status another sets should probably be two documents, because then the two edits cannot conflict.

Mango is the declarative query interface: POST /_find with a JSON selector, much like MongoDB's query language. It supports comparison, logical and array operators, sorting, field projection and pagination with bookmark. It needs indexes, created with POST /_index, and explain will tell you whether yours was used - a Mango query with no usable index falls back to scanning every document, which works on 200 documents and does not on 200,000.

Views are the older and more powerful mechanism. A view is a JavaScript map function, stored in a design document, that emits key-value pairs for each document; optionally a reduce function aggregates them. The emitted keys form a B-tree you can query by key, by range, and with grouping levels - which is where views beat Mango decisively. An array key [year, month, day] with group_level: 2 gives you monthly totals, and the same index gives daily totals at group_level: 3. There is no equivalent in Mango.

Views are incrementally built by background indexing. The index updates when documents change, but a query may need to wait for it, which is where the cost sits. Built-in reduce functions (_count, _sum, _stats) are implemented natively and are much faster than a JavaScript reduce - use them whenever they fit.

Choosing between them: Mango for ad-hoc filtering and anything an index can serve directly; views for aggregation, grouping levels, and the one query your application runs constantly. Views cost indexing time and disk; Mango costs scan risk.

Laboratory exercise 2 - two models, measured.

Design two schemas for the capstone's field survey application. The contrast that matters here is conflict surface: one with a survey response as a single large document (answers, photos metadata, review status, sync state all inside), and one split along editing boundaries - the response, the review and the sync state as separate documents sharing an id prefix.

Implement both. Write the representative queries: responses for one survey ordered by collection time, responses by collector, unreviewed responses, counts by site and month, and a full response with its review.

For each query, implement it both as a Mango selector with an index and as a view, and record which performs better and why. Use _explain on every Mango query and prove the index was used.

Then measure the conflict surface: simulate two clients editing the same response - one adding answers, one setting review status - in both models, and count the conflicts each produces.

Deliverable: both models, all queries in both Mango and view form with timings, every _explain output, the conflict surface measurement, and a page arguing for one model on the basis of conflicts as much as queries.

JS Example 1 154 lines
// ------------------------------------------------------------------
// One flat namespace. No collections. A `type` field on EVERY
// document is the universal convention.
// ------------------------------------------------------------------
// And the modelling pressure that is specific to CouchDB: the
// DOCUMENT is the unit of CONFLICT. Two devices editing different
// FIELDS of the same document still conflict. So split documents
// along the lines of WHO EDITS THEM.

// Model A - one big document. Two editors, guaranteed conflicts:
const modelA = {
  _id: "response:site-14:r001", type: "response",
  surveyId: "site-14", collectorId: "field-07",
  answers: [/* the collector edits these */],
  reviewStatus: "pending",          // the reviewer edits this
  reviewedBy: null,                 // ... and this
  syncState: {lastPush: "..."}      // ... and the device edits this
};

// Model B - split by editor. The same two edits CANNOT conflict:
const modelB = [
  { _id: "response:site-14:r001", type: "response",
    surveyId: "site-14", collectorId: "field-07", answers: [/*...*/] },
  { _id: "review:site-14:r001", type: "review",
    responseId: "response:site-14:r001", status: "pending", reviewedBy: null },
  { _id: "sync:tablet-03", type: "sync", lastPush: "..." }
];
// A shared id suffix makes them fetchable together with one
// _all_docs range query. Measure the conflict count in both; that
// number is the real argument.

// ------------------------------------------------------------------
// MANGO: declarative. Needs an index. CHECK that it used one.
// ------------------------------------------------------------------
//   curl -X POST http://.../survey/_index -H 'Content-Type: application/json' -d @-
const index = {
  index: { fields: ["type", "surveyId", "collectedAt"] },
  name: "type-survey-collected",
  type: "json"
};
// Field ORDER matters, as in any compound index: equality first.

//   curl -X POST http://.../survey/_find -H 'Content-Type: application/json' -d @-
const find = {
  selector: {
    type: "response",
    surveyId: "site-14",
    collectedAt: { $gte: "2026-11-01T00:00:00Z" }
  },
  fields: ["_id", "collectorId", "collectedAt"],
  sort: [{ collectedAt: "desc" }],
  limit: 50,
  use_index: ["_design/type-survey-collected", "type-survey-collected"]
};
// Response includes a `bookmark`; pass it back for the next page.
// There is no offset-based pagination worth using.

// ALWAYS _explain. This is the difference between a query and a scan:
//   curl -X POST http://.../survey/_explain -d @find.json
const explained = {
  dbname: "survey",
  index: { name: "type-survey-collected", type: "json" },   // GOOD
  // index: { name: "_all_docs", type: "special" },         // BAD:
  //   no usable index. Scans EVERY document. Fine on 200 docs,
  //   fatal on 200,000 - and it does not error, it just gets slow.
  mrargs: { include_docs: false, limit: 50 },
  selector: { /* ... */ }
};

// ------------------------------------------------------------------
// VIEWS: map/reduce in a design document. More powerful than Mango.
// ------------------------------------------------------------------
//   curl -X PUT http://.../survey/_design/reports \
//     -H 'Content-Type: application/json' -d @-
const designDoc = {
  _id: "_design/reports",
  language: "javascript",
  views: {
    // by_survey_time: range queries on [surveyId, collectedAt]
    by_survey_time: {
      map: function (doc) {
        if (doc.type === "response" && doc.surveyId) {
          emit([doc.surveyId, doc.collectedAt], {collector: doc.collectorId});
        }
      }.toString()
    },

    // THE thing views do that Mango cannot: GROUPING LEVELS.
    // One index answers "per year", "per month" AND "per day".
    counts_by_site_date: {
      map: function (doc) {
        if (doc.type === "response" && doc.collectedAt) {
          var d = doc.collectedAt.split("T")[0].split("-");
          emit([doc.surveyId, +d[0], +d[1], +d[2]], 1);
        }
      }.toString(),
      // BUILT-IN reduce. Implemented natively; far faster than a
      // JavaScript reduce. Use these whenever they fit:
      //   _count, _sum, _stats, _approx_count_distinct
      reduce: "_count"
    },

    unreviewed: {
      map: function (doc) {
        if (doc.type === "review" && doc.status === "pending") {
          emit(doc.responseId, null);
        }
      }.toString()
    }
  }
};

// Querying a view:
//   GET /survey/_design/reports/_view/by_survey_time
//       ?startkey=["site-14","2026-11-01"]
//       &endkey=["site-14","2026-12-01"]
//       &include_docs=true&limit=50
//
// GROUPING - the decisive feature. ONE index, three granularities:
//   ?group_level=1   -> per site
//   ?group_level=2   -> per site per YEAR
//   ?group_level=3   -> per site per MONTH
//   ?group_level=4   -> per site per DAY
//   ?group=true      -> the full key
// Mango has no equivalent. This is when you choose a view.

// ------------------------------------------------------------------
// Views are built by BACKGROUND INDEXING. Know the cost.
// ------------------------------------------------------------------
//   curl -s http://.../survey/_design/reports/_info | jq
const viewInfo = {
  name: "reports",
  view_index: {
    update_seq: 198000,       // the view is HERE
    // the database is at 200000, so 2,000 documents behind
    updater_running: true,
    sizes: { file: 48000000, active: 44000000 },
    updates_pending: { minimum: 2000, preferred: 2000, total: 2000 }
  }
};
// A query against a stale view WAITS for the indexer by default. The
// first query after a bulk load is therefore slow - sometimes very.
// stable=false&update=false returns immediately with STALE data,
// which is the right trade for a dashboard and the wrong one for a
// correctness check.

// ------------------------------------------------------------------
// Choosing between them.
// ------------------------------------------------------------------
//   MANGO   ad-hoc filtering; anything an index serves directly;
//           development speed. Cost: scan risk if the index is wrong.
//   VIEWS   aggregation, grouping levels, range scans on compound
//           keys, the one query the app runs constantly.
//           Cost: indexing time, disk, and staleness.

Open this example in the editor and change it. Nothing you type is saved.

Discussion

No questions on this topic yet. Sign in to ask the first one.