MongoDB更新嵌套数组报错16837:无法遍历元素的解决咨询
Hey there, let's break down your problem step by step. That error code 16837 is popping up because you're dealing with two nested arrays (segment_groups and segments), and the basic $ positional operator only handles one level of array matching. Here's how to fix your update query, plus some schema optimization tips to avoid headaches down the line.
Correct Update Query with Array Filters
MongoDB 3.6 and later introduced array filters, which let you explicitly target elements in nested arrays. This is exactly what you need here. Here's the working update command:
db.messages.update( // Optional: Add your document match condition here (e.g., {"_id": "T6GqWsi9qSxnyGzgC"}) // to target only specific documents instead of all in the collection {}, { $push: { "segment_groups.$[group].segments.$[segment].sequences": { "value_one": "value", "value_two": "value" } } }, { arrayFilters: [ // Target the specific segment with group_segment_id 597268 {"segment.group_segment_id": 597268} // Optional: Add another filter if you need to target a specific segment_group, e.g.: // {"group.grouping_id": 692335} ] } )
Why This Works
$[group]and$[segment]are placeholder identifiers that map to the conditions inarrayFilters.- The filter
{"segment.group_segment_id": 597268}tells MongoDB exactly which element in thesegmentsarray to modify, even though it's nested inside thesegment_groupsarray. - If you only want to update a single document (like the one with
_id: "T6GqWsi9qSxnyGzgC"), replace the empty{}in the first parameter with your document match condition—it'll be much more efficient than updating the entire collection.
Why Your Original Query Failed
Your initial update used segment_groups.segments.$.sequences, but MongoDB couldn't resolve the $ operator properly. Since segment_groups itself is an array, MongoDB didn't know which element in that array to target, leading to the "cannot use the part (segment_groups...) to traverse" error. The basic $ positional operator only works for one level of array nesting; you need array filters for deeper levels.
MongoDB Schema Optimization Best Practices
As a new MongoDB user, here are some tips to make your schema more manageable:
- Limit nested array depth: Arrays nested inside arrays (like
segment_groups > segments > sequences) can make queries and updates more complex. If you frequently target deep nested elements, consider flattening parts of the schema where possible. - Leverage unique identifiers: You already have
grouping_idandgroup_segment_id—great! Ensure these are unique where logical, and add indexes on them if you query by these fields often. For example:db.messages.createIndex({"segment_groups.segments.group_segment_id": 1}) - Watch document size limits: MongoDB has a 16MB maximum document size. If your
segment_groupsorsegmentsarrays are going to grow very large (hundreds/thousands of elements), consider splitting nested data into separate collections. For example, create asegmentscollection that references the parentmessagesdocument via amessage_idfield. - Align schema with query patterns: Design your schema based on how you'll read and write data. If you often retrieve full
segment_groupswith theirsegments, keeping them nested makes sense. If you frequently query individualsegmentsindependently, splitting into separate collections might be better.
内容的提问来源于stack exchange,提问作者colin rickels

