{
_id: "xPBc4By8FemDwTPqH",
friends: [{
username: "michael",
friendid: "154879",
friendlist: [{
randid: 54685,
friendname: "john",
illustrations: [{
randid: 178432,
image: "friend1.jpg"
}, {
randid: 545457,
image: "friend2.jpg"
}]
}]
}]
}
我的数据库结构如下所示。我想在插图数组中提取特定图像。我尝试了这段代码:
Collections.user.update(
{ "friends.friendid": 154879} ,
{ $pull: { 'friends.$[].friendlist.$[].illustrations': { "image": req.body.image } } } ,
function(err,result) {
if (err)
console.log(err);
else
res.send("Deleted");
})
此查询有效,但删除整个对象,而不仅仅是删除过滤的图像。我尝试过的另一个选项是设置image = undefined,但是它也不起作用。
有人可以帮我吗?
答案 0 :(得分:1)
编辑:
从3.6版开始,MongoDB包含了filtered positional operator,我认为这正是您所需要的:
Collections.user.update(
{ "friends.friendid": 154879 },
{ $pull: { "friends.$[elem1].friendlist.$[elem2].illustrations": { "image" : req.body.image } } },
{ arrayFilters: [
{ "elem1.friendlist.illustrations.image": req.body.image },
{ "elem2.illustrations.image": req.body.image }
]}
)
原始(和错误)答案:
我认为这段代码会起作用:
Collections.user.update(
{ "friends.friendid": 154879 } ,
{ $pull: { "friends.friendlist.illustrations.image": req.body.image } } ,
function(err,result) {
if (err) console.log(err);
else res.send("Deleted");
}
);