只是想知道实现这一目标的最佳方法是什么。我可以想到一些笨拙的方法,但它们似乎不对。
我想要做的是从文档中删除所有子子数组对象。像下面这样:
架构
schema {
person: Array<{
id: string;
posts: Array<{
id: string,
comments: Array<{
id: string
tagged_person_id: string;
}>
}>
}>
}
我正在寻找某种方法来删除每个帖子中每个人的所有评论tagged_person_id == some_id
。这不是我的实际用例,但它代表了相同的概念。
我知道如何使用$pull
从一个子文档的子数组中删除,但只是不确定如何在一个查询中完成所有这些,或者是否可能。
根据 JIRA 票证SERVER-1243和文档,从 MongoDB v3.5.12 开始,给出以下文档:
{
"posts" : [
{
"comments" : [
{
"tagged_person_id" : "x"
},
{
"tagged_person_id" : "y"
}
]
},
{
"comments" : [
{
"tagged_person_id" : "x"
}
]
},
{
"comments" : [
{
"tagged_person_id" : "y"
}
]
}
]
}
您可以运行此更新:
db.collection.update({}, {
$pull : {
"posts.$[].comments" : {"tagged_person_id": "x"}
}
})
为了删除所有注释,其中tagged_person_id
等于"x"
。
结果:
{
"posts" : [
{
"comments" : [
{
"tagged_person_id" : "y"
}
]
},
{
"comments" : []
},
{
"comments" : [
{
"tagged_person_id" : "y"
}
]
}
]
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句