N1QL - 如何向另一个数组中的每个数组元素添加新字段?

时间:2016-05-31 06:10:51

标签: arrays couchbase n1ql

我是Couchbase的新手,我得到了这个结构:

{ 
  items: [
    {
      id: "a1",
      subitems: [
        {
          id: "b1",
          name: "joe1"
        },
        {
          id: "b2",
          name: "joe2"
        }
      ] 
    }
  ],
  docType: "mydoc"   
}

我需要为子项目中的每个对象添加新字段。我知道如何使用1级数组=>

UPDATE default SET a.newField='blabla' FOR a IN items END where docType = 'mydoc';

它将产生:

{ 
  items: [
    {
      newField: "blabla",
      id: "a1",
      subitems: [
        {
          id: "b1",
          name: "joe1"
        },
        {
          id: "b2",
          name: "joe2"
        }
      ] 
    }
  ],
  docType: "mydoc"   
}  

但我需要这个结果:

{ 
  items: [
    {
      id: "a1",
      subitems: [
        {
          newField: "blabla",
          id: "b1",
          name: "joe1"
        },
        {
          newField: "blabla",
          id: "b2",
          name: "joe2"
        }
      ] 
    }
  ],
  docType: "mydoc"   
}  

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

使用即将推出的Couchbase 4.5.1,您应该可以:

UPDATE default
SET s.newField = 'newValue' FOR s IN ARRAY_FLATTEN(items[*].subitems, 1) END;

UPDATE default
SET s.newField = 'newValue' FOR s IN ARRAY_FLATTEN(ARRAY i.subitems FOR i IN items END, 1) END;

UPDATE default
SET i.subitems = ( ARRAY OBJECT_ADD(s, 'newField', 'blabla' ) FOR s IN i.subitems END ) FOR i IN items END;