给定MongoDB中的一些文档
[
{
"id": 1,
"items": [
{
"id": "T0001",
"x": 10,
"y": 10
},
{
"id": "T0002",
"x": 10,
"y": 5
},
{
"id": "T0003",
"x": 10,
"y": 10
},
{
"id": "T0004",
"x": 10,
"y": 20
}
]
},
{
"id": 2,
"items": [
{
"id": "T0001",
"x": 10,
"y": 5
},
{
"id": "T0002",
"x": 10,
"y": 15
}
]
}
]
我想删除id=1
文档中items.id="T0001"
和items.id="T0002"
的子文档。这可以用下面的命令来完成。
db.collection.update({
id: 1
},
{
$pull: {
items: {
id: {
$in: [
"T0001",
"T0002"
]
}
}
}
})
但是,如果我想再添加一个条件项。X === items.y"进入$pull
操作。(即只有子文档的id="T0001"
将被删除,因为它的x=10
和y=10
)
示例代码可以在这里找到https://mongoplayground.net/p/rYJp8wQPpcS。
谁能告诉我一些解决这个问题的方法?谢谢你!使用聚合管道进行更新会更容易。
-
$set
-设置items
字段。1.1。
$filter
-按条件筛选items
数组:1.1.1。
$not
-否定1.1.1.1的结果。1.1.1.1
$and
—满足["T0001", "T0002"]中id
的两个条件,且x
和y
相等。
db.collection.update({
id: 1
},
[
{
$set: {
items: {
$filter: {
input: "$items",
cond: {
$not: {
$and: [
{
$in: [
"$$this.id",
[
"T0001",
"T0002"
]
]
},
{
$eq: [
"$$this.x",
"$$this.y"
]
}
]
}
}
}
}
}
}
])
Mongo Playground示例