繁体   English   中英

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

[英]MongoDB: Update a sub-document in an array using an index

我的文档结构如下:

{ 
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!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM