我尝试更新文档中的特定对象。在此示例中,我想使用group.id = 'fdsfsFDSFdsfFdsFd'
和data.id = 'qqdWSdksFVfSVSSCD'
更改对象。
这意味着我想用{ "id" : "qqdWSdksFVfSVSSCD", "note 2" : "text" }
更新对象var newData = { "id" : "qqdWSdksFVfSVSSCD", "new one" : "anything" }
。
{
"_id" : "wLXDvjDvbsxzfxabR",
"group" : [
{
"id" : "dfDFSfdsFDSfdsFws",
"title" : "title 1",
"data" : [
{
"id" : "efBDEWVvfdvsvsdvs",
"note" : "text"
}
]
},
{
"id" : "fdsfsFDSFdsfFdsFd",
"title" : "title 2",
"data" : [
{
"id" : "WVvfsvVFSDWVDSVsv",
"note 1" : "text"
},
{
"id" : "qqdWSdksFVfSVSSCD",
"note 2" : "text"
},
{
"id" : "MZgsdgtscdvdsRsds",
"note 3" : "text"
}
]
}
]
}
那么我该如何准确访问这个对象?
Collection.update(
{ _id: 'wLXDvjDvbsxzfxabR' },
{ $set: { group.data: newData } } // group: fdsfsFDSFdsfFdsFd, data: qqdWSdksFVfSVSSCD
)
我没有让它更新嵌套数组元素......
答案 0 :(得分:3)
如果要更新阵列中的特定元素,则必须在查询中包含该元素。此外,在查询嵌套对象时,应将查询包装在引号中。
// Update element in array with id "dfDFSfdsFDSfdsFws"
Collection.update(
{ _id: "wLXDvjDvbsxzfxabR", "group.id": "dfDFSfdsFDSfdsFws"},
{$set: { "group.data": newData }}
);
答案 1 :(得分:1)
大卫的答案很接近:
Collection.update(
{ _id: "wLXDvjDvbsxzfxabR", "group.data.id": "qqdWSdksFVfSVSSCD"},
{$set: { "group.data": newData }}
);
答案 2 :(得分:1)
如果可以,我建议您更改文档架构,以便删除阵列中的嵌入式阵列。您可以将一个数组更改为JSON对象:
{
"_id" : "wLXDvjDvbsxzfxabR",
"group" : [
{
"id" : "dfDFSfdsFDSfdsFws",
"title" : "title 1",
"data" : {
"efBDEWVvfdvsvsdvs": {
"note" : "text"
}
}
},
{
"id" : "fdsfsFDSFdsfFdsFd",
"title" : "title 2",
"data" : {
"WVvfsvVFSDWVDSVsv": {
"note 1" : "text"
},
"qqdWSdksFVfSVSSCD": {
"note 2" : "text"
},
"MZgsdgtscdvdsRsds": {
"note 3" : "text"
}
}
}
]
}
使用此类架构,您可以使用此类查询更新数据字段中的特定对象:
db.collection.update(
{'group.id': 'fdsfsFDSFdsfFdsFd'},
{$set: {'group.$.data.qqdWSdksFVfSVSSCD': {"new one" : "anything"}}}
)