如何从CouchDB文档的视图中获取特定数据

时间:2019-06-29 19:41:40

标签: json database view nosql couchdb

我想计算我的文档中每个城市的建筑物数。这些文件与城市肯塔基州一起,我总共有6个城市。当我使用doc._id时,它返回id;但是当我使用doc.city时,它返回null。 如何显示每个城市的建筑总数?

CouchDB中的文档:

{
  "_id": "729489bb6702c473bb72254d13003f85",
  "_rev": "1-50da566becf84a0a686853290c2ad8a5",
  "Projects": [
    {
      "city": "Kentucky",
      "amount of people living": "853312",
      "overview": [
        {
          "building": "Center building",
          "amount of people": "150000",
          "teams": [
            {
              "party": "xd",
              "vote": "20000"
            },
            {
              "party": "zh",
              "vote": "20000"
            },
            {
              "party": "gh",
              "vote": "5000"
            },
            {
              "party": "sd",
              "vote": "20000"
            }
          ]
        },
        {
          "building": "Left building",
          "amount of people": "120000",
          "teams": [
            {
              "party": "gh",
              "vote": "20000"
            },
            {
              "party": "sw",
              "vote": "15000"
            },
            {
              "party": "gj",
              "vote": "5000"
            }
          ]
        },
        {
          "building": "Right building",
          "amount of people": "200000",
          "teams": [
            {
              "party": "sd",
              "vote": "20000"
            },
            {
              "party": "gs",
              "vote": "10000"
            },
            {
              "party": "er",
              "vote": "4000"
            }
          ]
        }
      ]
    }
  ]
}

我想要什么:

Key     | Value
---------------
Kentucky| 3      

我尝试使用的内容并返回null:

function (doc) {
  emit(doc._id, doc.building);
}

结果是什么

{"total_rows":3,"offset":0,"rows":[
{"id":"729489bb6702c473bb72254d13003f85","key":"729489bb6702c473bb72254d13003f85","value":null},
{"id":"729489bb6702c473bb72254d13007c22","key":"729489bb6702c473bb72254d13007c22","value":null},
{"id":"729489bb6702c473bb72254d130095fb","key":"729489bb6702c473bb72254d130095fb","value":null}
]}

1 个答案:

答案 0 :(得分:0)

您必须对CouchDB中的map和reduce函数有一个很好的了解。 Map函数会过滤您的数据并发出按键排序的键值对。 Reduce函数用于减少map函数的结果。主要编程在于reduce函数以获得所需的最终结果。

对于您的情况,Map函数应类似于

fun encodeToBase64()  {
    var st: NSString = "normalString"
    var data: NSData? = st.dataUsingEncoding(encoding = 
    NSUTF8StringEncoding)
    if (data != null) {
        var str = data.base64EncodedStringWithOptions(options = 0)
        println("base 64 string == $str")
    }
}

和减少功能应该

function (doc) {

  for( var i in doc.Projects){

  emit(doc.Projects[i].city,doc.Projects[i].overview);

  }
}