簡體   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