Reputation: 3
I have this document in couchdb, I wish to write a view which can emit key combination of original "_id" and the id within "Body" with the value as the body itself.
basically if "doc" is the json:
key [ _id, "key in Body" ]
value [ doc['_id']['Body'][key in Body]
Upvotes: 0
Views: 119
Reputation: 271
CouchDB has a detailed guide to views.
A views map function can emit multiple key-value pairs per document, so in your case you would emit each doc.Body
entry.
function(doc) {
if (doc.Body) {
// get an array of own property names in doc.Body
var bodies = Object.keys(doc.Body);
// loop over all the Body entries
bodies.forEach(function (body) {
// emit key-value for each entry
emit([doc._id, body], bodies[body].body);
});
}
}
To get all bodies from doc._id = "123"
:
http://my.couch.host/my-db/_design/docname/_view/viewname?startkey=["123"]&endkey=["123",{}]
To get the body of doc.Body.abc
from doc._id = "123"
:
http://my.couch.host/my-db/_design/docname/_view/viewname?startkey=["123","abc"]&endkey=["123","abc"]
See views collation and complex keys for more information.
Upvotes: 0