The field selection within an SQL query can be translated into a
corresponding view definition, either by adding the fields to
the emitted key (if the value is also used for selection in a
WHERE clause), or into the emitted value, if
the data is separate from the required query parameters.
For example, to get the sales data by country from each stored
document using the following map()
function:
function(doc, meta) { emit([doc.city, doc.sales], null); }
If you want to output information that can be used within a
reduce function, this should be specified in the value generated
by each emit() call. For example, to reduce
the sales figures the above map() function
could be rewritten as:
function(doc, meta) { emit(doc.city, doc.sales); }
In essence this does not produce significantly different output (albeit with a simplified key), but the information can now be reduced using the numerical value.
If you want to output data or field values completely separate to the query values, then these fields can be explicitly output within the value portion of the view. For example:
function(doc, meta) { emit(doc.city, [doc.name, doc.sales]); }
If the entire document for each item is required, load the document data after the view has been requested through the client library. For more information on this parameter and the performance impact, see Section 9.5.5, “View Writing Best Practice”.
Within a SELECT statement it is common
practice to include the primary key for a given record in the
output. Within a view this is not normally required, since the
document ID that generated each row is always included within
the view output.