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:
$setClause: We use placeholder identifiers ($[idx1],$[idx2]) instead of hardcoding array indices. These placeholders link directly to the filters defined inarrayFilters.- Array Filters:
- For
idx1: The$exprcondition checks that the element's index in thequestionsarray is exactly1, and we addidx1.answered: { $exists: false }to ensure we only update elements that don't already have theansweredkey. - For
idx2: Similarly, we target index2, but theanswered: { $exists: false }condition will fail for your existing third element (since it already hasanswered: "balloon"), so no update happens there.
- For
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
$infor 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
相关产品推荐
相关产品推荐

