CouchDB inner join by document field?
I have a question, i have 2 kind of documents, one of them is like this:
{
"type": "PageType",
"filename":开发者_运维知识库 "demo"
"content": "zzz"
}
and another one like this:
{
"type": "PageCommentType",
"refFilename": "demo"
"content": "some comment content"
}
i need to emit document that contains .comments field which is array of PageCommentType documents that i link on condition PageType document filename == PageCommentType document refFilename fields.
{
"filename": "demo",
"comments": [{}, {}, {}]
}
Anyone has any suggestions on how to implement it?
Thank you.
You need view collation. Emit both within the same view, using the filename
as the key and a type identifier to discriminate between comments and the original content:
function(doc) {
if (doc.type == "PageType") emit([doc.filename,0],doc.content);
if (doc.type == "PageCommentType") emit[doc.refFilename,1],doc.content);
}
When looking for the document demo
and its comments, run a query with startkey=["demo",0]
and endkey=["demo",1]
: you will get the page content followed by all the comments.
Once you have all the data you want, but it's not in the right format, you are almost done. Simply write a _list
function to read all the rows and output the final JSON document with the structure/schema that you need.
精彩评论