Couchdb 如何在特定日期后获取记录
我正在尝试获取“effectiveDateOfAction”字段大于2017年10月的记录。请查找以下3条记录Couchdb 如何在特定日期后获取记录,couchdb,couchdb-mango,fauxton,Couchdb,Couchdb Mango,Fauxton,我正在尝试获取“effectiveDateOfAction”字段大于2017年10月的记录。请查找以下3条记录 { "_id": "TRAN001", "_rev": "13-59a53069c1ebd6ecfc23ca1dea0ba28f", "effectiveDateOfAction": "10-30-2018", "employeeName": "Kumar,Vinoth", "transferReportID": "TRAN001", "~version": "76:0"
{
"_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"
}
请在下面找到我尝试的查询。我正在使用Fauxton项目进行检查
{"selector": {"$and": [{"transferReportID": {"$ne": null}},{"effectiveDateOfAction": {"$gt": "10-31-2017"}}]}}
请帮助我获取正确的查询。由于JSON中没有本机日期类型,因此在查询时以有意义的格式存储日期非常重要。“月-日-年”格式在为美国观众呈现日期时可能很有用,但在查询时没有什么意义 我建议采用“YYYY-MM-DD”格式,例如“2018-10-30”。这将存储与以前相同的数据,但排序顺序恰好是日期顺序,因为年长于月,月长于天 然后可以使用“$gte”运算符使用查询:
{
"selector": {
"effectiveDateOfAction": {
"$gte": "2018-10-01"
}
}
}
其内容为“获取其'effectiveDateOfAction'字段大于或等于2018年10月1日的文档”
请参阅如何在CouchDB中存储和查询日期。如Glyn Bird所说,如果可能,将日期格式更改为可排序的格式。我建议使用,JSON(如Javascript)更倾向于使用这种格式 如果不能更改数据,可以创建一个视图,将日期转换为可排序格式 示例:将类似于以下内容的设计文档放入数据库
{
_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=true
param将真实文档包括在内
/my-database/_design/employees/_view/by_action_date?include_docs=true
然后,您还可以使用startkey
和endkey
参数来限制特定的时间范围:
/my-database/_design/employees/_view/by_action_date?include_docs=true&startkey="2018-10-01"&endkey="2018-10-31"
这将返回您的
TRAN001
和TRAN002
文档。“$gt:“10-31-2017”
是一个字典字符串比较,因此10-31-2018
将大于01-01-2019
。您可能需要创建一个视图,该视图将按日期排序发送数据(请参阅)@Enno谢谢您的回复。我是coach DB query的新手,如果可能的话,请您分享一下这方面的工作示例。