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

MongoDB按索引更新数组元素:仅为无指定键的元素添加字段

How to Update Specific Array Elements Only When a Key Doesn't Exist in MongoDB

Absolutely, you can use ArrayFilters to achieve this exact behavior—this is the perfect tool for conditional updates on specific array elements. Here's how to adjust your query to skip elements that already have the answered key:

Working Query

db.collection.update(
  { "key": 1 },
  { 
    $set: { 
      "questions.$[idx1].answered": "second answer",
      "questions.$[idx2].answered": "third answer"
    } 
  },
  {
    arrayFilters: [
      {
        "$expr": { $eq: [{ $indexOfArray: ["$questions", "$$idx1"] }, 1] },
        "idx1.answered": { $exists: false }
      },
      {
        "$expr": { $eq: [{ $indexOfArray: ["$questions", "$$idx2"] }, 2] },
        "idx2.answered": { $exists: false }
      }
    ]
  }
)

Breakdown of the Solution

Let's walk through what each part does:

  • $set Clause: We use placeholder identifiers ($[idx1], $[idx2]) instead of hardcoding array indices. These placeholders link directly to the filters defined in arrayFilters.
  • Array Filters:
    • For idx1: The $expr condition checks that the element's index in the questions array is exactly 1, and we add idx1.answered: { $exists: false } to ensure we only update elements that don't already have the answered key.
    • For idx2: Similarly, we target index 2, but the answered: { $exists: false } condition will fail for your existing third element (since it already has answered: "balloon"), so no update happens there.

Result

After running this query, your document will match your desired output exactly:

{ 
  "key": 1, 
  "questions": [ 
    { "text": "first" }, 
    { "text": "second", "answered": "second answer" },
    { "text": "third", "answered": "balloon" }
  ]
}

Quick Notes

  • If you ever need to update multiple indices with the same value, you could combine them into a single filter using $in for the index check (e.g., $eq: [{ $indexOfArray: ["$questions", "$$elem"] }, { $in: [1,2] }]), but since your update values are different here, separate filters are necessary.
  • This approach ensures you only modify the exact elements you intend to, without overwriting existing data.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 23:37:43