我的 mongo 数据库中有以下名为 music 的对象。
我想更新 Grunge 的流派
乐队名字叫涅槃
专辑名称是Nevermind
轨道顺序为1
并将轨道名称更改为“Smells Like Teen Spirit!”。
我尝试过使用位置运算符,但不能
想办法。
{
genre : "Grunge",
bands : [ {
name : "Nirvana",
albums : [ {
name : "Nevermind",
tracks : [ {
name : "Smell Like Teen Spirit",
order : 1,
duration : 301
},
{
name : "In Bloom",
order : 2,
duration : 254
} ]
},
{
name : "In Utero",
tracks : [ {
name : "Server the Servants",
order : 1,
duration : 216
},
{
name : "Scentless Apprentice",
order : 2,
duration : 254
} ]
} ]
},
{
name : "Karma++ : A Nirvina Tribute Band",
albums : [ {
name : "Nevermind",
tracks : [ {
name : "Smell Like Teen Spirit",
order : 1,
duration : 301
},
{
name : "In Bloom",
order : 2,
duration : 254
} ]
},
{
name : "In Utero",
tracks : [ {
name : "Server the Servants",
order : 1,
duration : 216
},
{
name : "Scentless Apprentice",
order : 2,
duration : 254
} ]
} ]
} ]
}
最佳答案
不幸的是,目前每次更新只能使用一个“$”位置。这将更新限制为单个嵌入式数组,类似于文档中的示例:http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator (从您的帖子中,您似乎已经找到了这个,但为了方便其他阅读此帖子的用户,我已包含该链接。)
为了进行更新,您必须知道以下三个中两个的位置:乐队在“bands”数组中的位置、专辑在专辑数组中的位置或位置“tracks”数组中的轨道。
对此功能有一个功能请求,它计划在 2.3.0 版本中使用(尽管这可能会发生变化)。
https://jira.mongodb.org/browse/SERVER-831 《定位运算符匹配嵌套数组》
暂时,您将必须知道子文档在三个数组中的两个中的位置:
db.music.update({genre : "Grunge", "bands.name" : "Nirvana"}, {$set:{"bands.$.albums.0.tracks.0.name":"Smells Like Teen Spirit!"}})
db.music.update({genre : "Grunge", "bands.0.albums.name" : "Nevermind"}, {$set:{"bands.0.albums.$.tracks.0.name":"Smells Like Teen Spirit!"}})
或
db.music.update({genre : "Grunge", "bands.0.albums.0.tracks.order" : 1}, {$set:{"bands.0.albums.0.tracks.$.name":"Smells Like Teen Spirit!"}})
关于MongoDB 更新深度数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10341151/