我在mongodb中嵌入了文档如何只删除一个地址,其中pincode:140901并更新其中pincode为:152364
db.add_fun.insert({
"_id" : ObjectId("5a82e6dc1139b572569fa785"),
"name" : "Vikas",
"salary" : 72.0,
"address" : [
{
"address_id" : ObjectId("5a82f0e51139b572569fa78c"),
"address" : "Mullanpur ",
"pincode" : "140901",
"country" : "India"
},
{
"address_id" : ObjectId("5a82f0e51139b572569fa78d"),
"address" : "mohali ",
"pincode" : "152364",
"country" : "India"
}
]
})
我试试这个但没有工作
db.add_fun.update({},
{
$pull: {
address: {
$elemMatch: {
pincode: "140901"
}
}
}
},
{
multi:true
}
)
想要删除此
{
"address_id" : ObjectId("5a82f0e51139b572569fa78c"),
"address" : "Mullanpur ",
"pincode" : "140901",
"country" : "India"
},
并希望获得此结果
{
"_id" : ObjectId("5a82e6dc1139b572569fa785"),
"name" : "Vikas",
"salary" : 72.0,
"address" : [
{
"address_id" : ObjectId("5a82f0e51139b572569fa78d"),
"address" : "mohali ",
"pincode" : "152364",
"country" : "India"
}
]
}
答案 0 :(得分:3)
不需要$elemMAtch
,只是数组中子文档的条件。在你的情况下:
db.add_fun.update(
{},
{ $pull: {
address: {
pincode: "140901"
}
} },
{ multi:true }
);
文档:https://docs.mongodb.com/manual/reference/operator/update/pull/
答案 1 :(得分:0)
只需在地址栏中添加一个查询,以确保您只更新数组:
db.add_fun.update(
{ address: { $type: 4 }},
{ $pull: {
address: {
pincode: "140901"
}
} },
{ multi:true }
);
答案 2 :(得分:0)
请允许我建议您通过ObjectId删除对象以保证唯一性。
db.add_fun.update(
{ },
{ $pull: {
address: {
"address_id" : ObjectId("5a82f0e51139b572569fa78c")
}
} },
{ multi:true }
);