如何在 couchbase 中添加一个键值,其中该值是从文档中已经存在的键值派生的

How to add a key value in couchbase where the value is derived from an already existing key value in the document

我在 couchbase 中有一个 json 文档,其结构如下所示

"root": {
          "type": "TEST",
          "parameters": {
            "numbers": [
              "1",
              "2-001",
              "3",
              "2-001",
              "5-002"
           ] 
          }
        }

我需要添加一个新的键值对并使文档看起来像这样

"root": {
          "type": "TEST",
          "parameters": {
            "numbers": [
              "1",
              "2-001",
              "3",
              "2-001",
              "5-002"
           ],
          "unique": [
              "1",
              "2",  
              "3",
              "5"
          ] 
         }
        }

我应该去掉 - 之后的所有内容,select 里面存在的独特元素。

如果您想使用 N1QL 执行此操作,可以使用 ARRAY transformation combined with ARRAY_DISTINCT. The transformation will be up to you. You could use one of the REGEXP_ functions or something simple like a SPLIT。例如:

select ARRAY_DISTINCT(ARRAY SPLIT(v,"-")[0] FOR v IN d.root.parameters.numbers END) as `unique`, d.root.parameters.numbers
from mybucket d;

这将 return 文档的形式:

[
  {
    "numbers": [
      "1",
      "2-001",
      "3",
      "2-001",
      "5-002"
    ],
    "unique": [
      "1",
      "2",
      "3",
      "5"
    ]
  }
]

如果您想对文档进行实际更改,可以将 SELECT 变成 UPDATE:

UPDATE mybucket
SET root.`unique` = ARRAY_DISTINCT(ARRAY SPLIT(v,"-")[0] FOR v IN root.parameters.numbers END)
where root.`unique` is missing;