How to get from CouchDB only certain fields of certain documents with a single request?

亡梦爱人 提交于 2019-12-02 06:02:19

问题


create a view that return only a subset of values from a document, each with its key and value within a json string. like if one given view returns a document as this following, Is it possible to get some fields information for a one request? thank you { "total_rows":10, "offset":3, "rows":[{ "id":"doc1", "key":"abc123", "value": { "_id":"aaaa", "_rev":"bbb", "field1":"abc", "field2":"bcd", "field3":"cde", "field4":"123", "field5":"789", "field6":"aa@email.com", "field7":"ttt", "field8":"iii", "field9":[{ "field91":"tyui", "field92":"55555" }], "field10"::"0000", "field11"::"55555", "field12"::"0030"......... } } I just want to create a view that returns some fields only the following: { "field1":"abc", "field2":"bcd", "field3":"cde", "field4":"123", "field5":"789", "field6":"aa@email.com", "field7":"ttt", "field8":"iii", "field9":[{ "field91":"tyui", "field92":"55555" }] }


回答1:


A map function that emits a new document with selected fields only. As an example, let's map field1 (a string) and field9 (an array) only:

function map(doc) {
  emit(doc._id, {
    field1: doc.field1, 
    field9: doc.field9
  });
}

In the above example, each document will be fired with a key being the original doc ID and the value being the mapped fields you require. This is useful if you are planning to add a reduce function later.

Depending on your use case, you may just want to emit the mapped objects:

function map(doc) {
  emit({
    field1: doc.field1, 
    field9: doc.field9
  });
}

Please see http://guide.couchdb.org/draft/views.html The documentation on building data views is pretty good, you can discover a lot by experimenting..



来源:https://stackoverflow.com/questions/37337113/how-to-get-from-couchdb-only-certain-fields-of-certain-documents-with-a-single-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!