Couchbase数组查询:如何从status_history数组中获取status字段
如何从Couchbase数组
status_history中提取status字段? 嘿,针对你在Couchbase里从数组status_history提取status字段的需求,我结合你已经用到的“查询今日文档”场景,整理了几种实用的查询方式:
首先先假设你的文档结构大概是这样的(方便对照理解):
{ "history": { "date": "today" }, "status_history": [ {"status": "active", "timestamp": "2024-05-20T09:00:00"}, {"status": "inactive", "timestamp": "2024-05-20T13:00:00"}, {"status": "pending", "timestamp": "2024-05-20T17:00:00"} ] }
1. 将所有status提取为一个新数组返回
如果希望把每个文档里status_history中的所有status值打包成一个数组返回,可以用Couchbase的ARRAY表达式:
SELECT ARRAY sh.status FOR sh IN status_history END AS status_list FROM `my_bucket` WHERE history.date = "today"
查询结果会是类似这样的结构:
[ { "status_list": ["active", "inactive", "pending"] } ]
2. 展开数组,每条status单独成一行
要是你需要把数组里的每个status拆成独立的行(方便后续统计或单独处理),就用UNNEST关键字来展开数组:
SELECT sh.status FROM `my_bucket` UNNEST status_history sh WHERE history.date = "today"
这种方式的返回结果会是多行,每行对应一个status值:
[ {"status": "active"}, {"status": "inactive"}, {"status": "pending"} ]
3. 提取数组中满足特定条件的status
如果只需要status_history里符合某些条件的status(比如特定时间戳的状态),可以在ARRAY表达式里加上过滤逻辑:
SELECT ARRAY sh.status FOR sh IN status_history WHERE DATE_TRUNC_STR(sh.timestamp, 'day') = "today" END AS filtered_status FROM `my_bucket` WHERE history.date = "today"
这个查询会只保留status_history中时间戳属于今日的status值,返回一个过滤后的数组。
小提示:如果status_history是空数组,上述查询也不会报错——用ARRAY方式会返回空数组,用UNNEST方式则不会返回对应文档的行。
内容的提问来源于stack exchange,提问作者SuperCow
相关产品推荐
相关产品推荐

