gpt4 book ai didi

arrays - MongoDB:使用索引更新数组中的子文档

转载 作者:可可西里 更新时间:2023-11-01 09:52:19 25 4
gpt4 key购买 nike

我的文档结构如下:

{ 
key: "apples002",

main: [
{q: "Is the apple green?", a1: "The apple is not green.", a2: "No."},

{q: "What color is the apple?", a1: "The apple is yellow.", a2: "Yellow."}
],

alt: [

{q: "What color is the apple?", a1: "The apple is red."},

{q: "Is the apple yellow?", a1: “The apple is yellow.”, a2: “Yes.”}
]

我见过几个更新子文档字段的例子,但大多数都是子文档具有唯一 ID 的情况。我还学会了如何通过索引引用其中一个子文档,例如更新 main 上面的 q 字段(第一个元素):

myDB.update({key: 'apples002'}, {$set: {'main.0.q': 'Updated question goes here'}})

所以在我的例子中,我想用一个变量来代替上面的数组索引 0。我曾尝试创建一个具有正确字符串值的本地 var 并使用它代替上面的“main.0.q”,但这不起作用。有什么想法吗?

最佳答案

@JohnnyHK,你是对的,它本质上是一个副本。昨天我试了又试,但找不到这个信息,所以我认为以几种形式提出这个问题是个不错的主意。

我已经改编了 JohnnyHK 的回答来展示我必须做些什么才能使上述更新与索引变量一起工作:

    var setModifier = { $set: {} };

setModifier.$set['main.' + myIndex + '.q'] = 'Updated question goes here.';

PL.update({key: 'apples002'}, setModifier);

谢谢 JohnnyHK!

关于arrays - MongoDB:使用索引更新数组中的子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22016788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com