使用$pull从mongo中的文档中删除孙元素



正如标题所示,我有一个文档,它包含一个对象数组(注释(中的对象数组。用户可以对每个笔记发表评论,但我也在尝试添加一个删除功能来删除每个笔记上的评论。

scheduleCollection.update_one({'date': date},
{'$pull': {"note.$": {"comment.$.commentId": commentId}}}):

这是我目前拥有的,但我收到了这个错误:

位置运算符未从查询中找到所需的匹配项。,完整错误:{'index':0,'code':2,'errmsg':'位置运算符未从查询中找到所需的匹配项。'}

我尝试过$pull中的各种组合,但都没有成功。

数据结构看起来像:

{
"date": "03-31-2022",
"note": [{
"comment": [{
"commentId": "uuid",
"comment": "etc"
}]
}]
}

看看它是否有帮助:

{
"_id" : ObjectId("6247960b5b63591be3ddf3f9"),
"date" : ISODate("2022-04-01T21:17:15.570-03:00"),
"note" : [
{
"comment" : [
{
"commentId" : ObjectId("6247960b5b63591be3ddf3f8"),
"comment" : "etc"
}
]
}
]},

db.pull.update(
{ 'note.comment.commentId': ObjectId("6247960b5b63591be3ddf3f8") },
{
$unset: {
"note.0.comment.0.comment": true
}
},
{ multi: 1 })
{
"_id" : ObjectId("6247960b5b63591be3ddf3f9"),
"date" : ISODate("2022-04-01T21:17:15.570-03:00"),
"note" : [
{
"comment" : [
{
"commentId" : ObjectId("6247960b5b63591be3ddf3f8")
}
]
}
]}

或:

db.pull.update(
{ 'note.comment.commentId': ObjectId("624799285b63591be3ddf3fd") },
{
$pull:
{
note:
{
comment: { $elemMatch: { commentId: { $eq: ObjectId("624799285b63591be3ddf3fd") } } }
}
}
})
update_one({'note.comment.commentId': commentId},
{'$pull': {'note.$.comment': {'commentId': {'$eq': commentId}}}}):

是我找到的解决方案。

相关内容

最新更新