【发布时间】:2021-02-18 23:22:39
【问题描述】:
这是我的集合对象结构
"_id" : ObjectId("xxxxxxxxxxxxxxxxxxxxxxxx"),
"Name": "HelloWorld",
"OtherFields": "OtherValues",
"Projects" : [
{
"Project" : {
"key" : 111
},
"Category" : [
{
"No" : "123"
},
{
"No" : "987"
}
]
},
{
"Project" : {
"key" : 222
},
"Category" : [
{
"No" : "123"
},
{
"No" : "987"
}
]
}
]
我想删除项目中键为 111 的类别编号「123」的元素
我做的更接近的事情是
db.project_collection.updateOne({"_id": ObjectId("collection_obj_id")}, {"$pull": { "Projects": {"$and": [ {"Project.key": 111)}, {"Category.No": "123"} ] }} })
此命令删除 "Projects" 对象内的整个元素
但我只想删除 "Projects" → "Category" → [0] 没有 123 的子元素。
当我尝试将"$pull" 之后的"Projects" 更改为"Projects.Category" 或"Projects.$.Category" 之类的东西时
The positional operator did not find the match needed from the query
发生错误。
那么是否可以在不创建自己的后端逻辑的情况下删除子元素?
【问题讨论】:
-
您需要使用数组更新运算符positional $。
-
我已经尝试过 Projects.$, Projects.$.Category.$, Projects.Category.$, Projects.$.Category 没有运气
-
是的,你可以试试下面 J.F 的答案。另一个例子 here 使用
$pull。 -
标记重复项中的一个答案指示
db.collection.update({ _id: "xxxxxxxxxxxxxxxxxxxxxxxx" }, { $pull: { "Projects.$[elem].Category": { "No": "123" } } }, { arrayFilters: [ { "elem.Project.key": 111 } ] })形式的解决方案
标签: mongodb