You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GraphQL中更新多层嵌套数组内的指定字段值

不同场景下的访问/更新语句

1. 原生JavaScript写法

// 定位目标option
const targetOption = data.item.options.find(opt => opt.label === 'Top');
// 定位目标spec
const targetSpec = targetOption.specs.find(spec => spec.label === 'Right');
// 直接更新value属性
targetSpec.value = '你要设置的新值';

// 可选链式写法(避免字段不存在时报错)
const targetValue = data.item.options?.find(opt => opt.label === 'Top')?.specs?.find(spec => spec.label === 'Right')?.value;

2. Python写法

# 定位目标option
target_option = next(opt for opt in data['item']['options'] if opt['label'] == 'Top')
# 定位目标spec
target_spec = next(spec for spec in target_option['specs'] if spec['label'] == 'Right')
# 更新value属性
target_spec['value'] = '你要设置的新值'

3. MongoDB更新语句

如果该结构存储在MongoDB文档中,更新语句如下:

db.collection.updateOne(
  { "item.options.label": "Top" },
  { $set: { "item.options.$[opt].specs.$[spec].value": "新值" } },
  {
    arrayFilters: [
      { "opt.label": "Top" },
      { "spec.label": "Right" }
    ]
  }
)

4. JSONPath定位写法

用JSONPath直接定位目标节点的语法:

$..options[?(@.label=='Top')].specs[?(@.label=='Right')].value

内容的提问来源于stack exchange,提问作者jakey_dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 07:57:03