我正在尝试使用以下结构更新我的mongo集合
{
"_id" : "T6GqWsi9qSxnyGzgC",
"spec_name" : "test",
"version" : "test",
"message_type" : "test",
"message_trigger" : "test",
"segments" : [
{
"segment_id" : "MSH",
"sequences" : [
{
"dataType" : "ST",
"optionality" : "R",
"name" : "Field Seperator"
},
{
"dataType" : "ST",
"optionality" : "R",
"name" : "Encoding Characters"
},
{
"dataType" : "HD",
"optionality" : "O",
"name" : "Sending Application"
},
{
"dataType" : "HD",
"optionality" : "O",
"name" : "Sending Facility"
},
{
"dataType" : "HD",
"optionality" : "O",
"name" : "Receiving Application"
},
{
"dataType" : "HD",
"optionality" : "O",
"name" : "Receiving Facility"
},
{
"dataType" : "TS",
"optionality" : "O",
"name" : "Data/Time Of Message"
},
{
"dataType" : "ST",
"optionality" : "O",
"name" : "Security"
},
{
"dataType" : "CM",
"optionality" : "R",
"name" : "Message Type"
},
{
"dataType" : "ST",
"optionality" : "R",
"name" : "Message Control ID"
},
{
"dataType" : "PT",
"optionality" : "R",
"name" : "Processing ID"
},
{
"dataType" : "NM",
"optionality" : "O",
"name" : "Sequence ID"
},
{
"dataType" : "ST",
"optionality" : "O",
"name" : "Continuation Pointer"
},
{
"dataType" : "ID",
"optionality" : "O",
"name" : "Accept Acknowledgment Type"
},
{
"dataType" : "ID",
"optionality" : "O",
"name" : "Application Acknowledgment Type"
},
{
"dataType" : "ID",
"optionality" : "O",
"name" : "Country Code"
},
{
"dataType" : "ID",
"optionality" : "O",
"name" : "Character Set"
},
{
"dataType" : "CE",
"optionality" : "O",
"name" : "Principal Language Of Message"
}
]
}
],
"segment_groups" : [
{
"grouping_id" : 692335,
"segments" : [
{
"segment_id" : "test",
"group_segment_id" : 597268,
"sequences" : [ ]
}
]
}
]
}
我希望附加{value_one:" value",value_two:" value" }进入segment_groups内的序列数组。我的查询如下:
db.messages.update({"segment_groups.segments.group_segment_id": 597268},{$push:{ "segment_groups.segments.$.sequences":{"value_one":"value", "value_two":"value"}}})
尝试此操作时出现错误:
"code" : 16837,
"errmsg" : "cannot use the part (segment_groups of segment_groups.segments.0.sequences) to traverse the element ({segment_groups: [ { grouping_id: 692335, segments: [ { segment_id: \"test\", group_segment_id: 597268, sequences: [] } ] } ]})"
enter code here
我已经在这个问题上待了一天,并没有找到任何关于如何解决或如何重组我的收藏的合理建议。我是mongo的新手,在构建时我不了解最佳实践,因此任何使这个更好的解决方案所需的方法都是有价值的。
答案 0 :(得分:1)
你遇到的问题是你的模型有两层嵌套数组(segments_groups
和segments
),Mongo无法弄清楚该数组中哪些项需要更新。
在MongoDB 3.6中,使用arrayFilters / positional filtered operator可以很容易地解决这个问题。在更新路径中,为每个数组指定代表一个特定项的占位符,然后必须添加匹配条件arrayFilters
,以帮助MongoDB查找要更新的项目。在你的情况下:
db.messages.update({"_id" : "T6GqWsi9qSxnyGzgC"},
{ $push: { "segment_groups.$[sg].segments.$[s].sequences": {"value_one":"value", "value_two":"value"} } },
{ arrayFilters: [ { "sg.grouping_id": 692335 }, { "s.group_segment_id": 597268 } ] })
所以$[sg]
是一个segment_group
,$[s]
代表一个细分。