0

我正在尝试获取“ effectiveDateOfAction ”字段大于 Oct'2017 的记录。请找到以下 3 条记录。

{
 "_id": "TRAN001",
 "_rev": "13-59a53069c1ebd6ecfc23ca1dea0ba28f",
 "effectiveDateOfAction": "10-30-2018",
 "employeeName": "Kumar,Vinoth",
 "transferReportID": "TRAN001",
 "~version": "76:0"
}

{
 "_id": "TRAN001",
 "_rev": "12-c320c61168f5d6d020f971124cb395f2",
 "effectiveDateOfAction": "05-10-2018",
 "employeeName": "Vinoth",
 "transferReportID": "TRAN002",
 "~version": "77:0"
}

{
 "_id": "TRAN003",
 "_rev": "16-567a15e9ea7e2349d4c24816e7eafda3",
 "effectiveDateOfAction": "10-20-2017",
 "employeeName": "Kumar",
 "transferReportID": "TRAN003",
 "~version": "78:0"
}

请在下面找到我尝试过的查询。我正在使用 Project Fauxton 进行检查。

{"selector": {"$and": [{"transferReportID": {"$ne": null}},{"effectiveDateOfAction": {"$gt": "10-31-2017"}}]}}

请帮助我获得正确的查询。

4

2 回答 2

1

由于 JSON 中没有本机日期类型,因此以在查询时有意义的格式存储日期非常重要。在为美国观众呈现日期时,“月-日-年”格式可能很有用,但对于查询来说意义不大。

我建议使用“YYYY-MM-DD”格式,例如“2018-10-30”。这存储与以前相同的数据,但排序顺序恰好是日期顺序,因为年长于月,月长于日。

然后,您可以使用“$gte”运算符进行查询:

{
  "selector": {
    "effectiveDateOfAction": {
      "$gte": "2018-10-01"
     }
  }
}

这读作“获取 'effectiveDateOfAction' 字段大于或等于 2018 年 10 月 1 日的文档”。

请参阅此博客文章,了解如何在 CouchDB 中存储和查询日期。

于 2018-11-23T11:00:39.783 回答
0

如 Glyn Bird 所说,如果可能,请将您的日期格式更改为可排序的形式。我建议使用ISO_8601,这是 JSON 的首选(例如 Javascript Date.toJSON)。

如果您无法更改数据,您可以创建一个视图,将您的日期转换为可排序的格式。

示例:将类似于以下内容的设计文档放入您的数据库

{
  _id: '_design/employees',
  views: {
    by_action_date: {
      map: "function (doc) {\n        if (doc.effectiveDateOfAction && doc.employeeName) { // filter for employee docs\n          var dt = doc.effectiveDateOfAction.split('-'); // parse your date format\n          emit(`${dt[2]}-${dt[1]}-${dt[0]}`); // emit iso date as key\n        }\n      }"
    }
  }
}

map函数必须在文档中以字符串形式给出,其格式为:

function(doc) {
    if (doc.effectiveDateOfAction && doc.employeeName) { // filter for employee docs
      var dt = doc.effectiveDateOfAction.split('-'); // parse your date format
      emit(`${dt[2]}-${dt[1]}-${dt[0]}`); // emit iso date as key
    }
  }

然后,您可以查询它以对您的员工进行排序:
使用include_docs = trueparam 将您的真实文档包含在内。

/my-database/_design/employees/_view/by_action_date?include_docs=true

然后,您还可以使用startkeyendkey参数来限制特定的时间范围:

/my-database/_design/employees/_view/by_action_date?include_docs=true&startkey="2018-10-01"&endkey="2018-10-31"

这将返回您的TRAN001TRAN002文件。

于 2018-11-28T16:03:01.093 回答