问题描述
这是我的数据结构:
db.getCollection('competitionmatches').find()
{
"_id" : ObjectId("5d2d9eed5972a9367cd5010a"),"matches" : [
{
"id" : 200000,"utcDate" : "","minute" : null,"homeTeam" : {
"id" : 808,"coach" : {},},"goals" : [{},{}}],{...},],"otherField": []
},
我要删除的是那些字段:minute
中所有条目的所有coach
中的goals
,matches
和competitionmatches
。
我在Robo 3T中尝试了以下成功的方法:
db.getCollection('competitionmatches').update({},{$unset: {"otherField":""}})
如果我通过otherField
,则会很好地删除matches
的每个元素中的整个数组multi:true
(为便于阅读,在此删除)。
但是当我尝试:
db.getCollection('competitionmatches').update({},{$unset: {"matches.$[].goals":""}})
或
db.getCollection('competitionmatches').update({},{$unset: {"matches.$[].minute":""}})
我收到一条成功消息Updated 1 existing record(s) in 3ms
,但记录保持不变,minute
或goals
未被删除。
我从Remove a field from all elements in array in mongodb得到了这个答案,并将我的mongo版本从3.4更新到3.6,因为svr说$[]
是在3.6中引入的,并在docs中显示
取消设置有效,但路径似乎是我更新的错误部分。
"matches.$.goals"
返回错误,并且matches.[].goals
也没有任何影响。
我什至想知道是否可能有一些缓存,但这没有多大意义,因为otherField
上的未设置得到很好的执行。
我也怀疑更新是否顺利,但据我所知,使用数据库的应用程序运行良好。
解决方法
此更新无法使用$
或$[]
访问直接数组字段,我们需要提供查询以在数组中进行匹配,
db.getCollection('competitionmatches').update(
// it requires to specify any one field match condition in query part
{ "matches.goals": { $exists: true } },{
$unset: {
"matches.$[].minute": true // pass true
"matches.$[].homeTeam.coach": true // pass true
"matches.$[].goals": true // pass true
}
}
);
Mongo shell
> db.upd22.find()
[
{
_id: ObjectId("5d2d9eed5972a9367cd5010a"),matches: [
{
id: 200000,utcDate: '',minute: null,homeTeam: { id: 808,coach: {} },goals: [ {},{} ]
},{
id: 300000,{} ]
}
]
},{
_id: ObjectId("5d2d9eed5972a9367cd5010b"),matches: [
{
id: 400000,{
id: 500000,> homeTeam: { id: 808,{} ]
}
]
}
]
> db.getCollection('upd22').update(
... { "matches.goals": { $exists: true } },... {
..... $unset: {
....... "matches.$[].minute": true,....... "matches.$[].goals": true
....... }
..... },... { multi: false }
... )
{
acknowledged: 1,insertedId: null,matchedCount: 1,modifiedCount: 1,upsertedCount: 0
}
> db.upd22.find()
[
{
_id: ObjectId("5d2d9eed5972a9367cd5010a"),matches: [
{ id: 200000,coach: {} } },{ id: 300000,coach: {} } }
]
},{} ]
}
]
}
]
>